Lesson 23: Viewing the first and last lines in files¶
In addition to the cat
command (to print the entire file contents),
commands head and
tail can be used to display
the first or last line(s), ignoring the rest of the file contents.
To print the first line(s) from a file, use the head
command with the
-n NUM
switch (where NUM is the number of lines to print, 10 by
default).
[learner planets]$ head -n 2 earth.txt
Earth is the third planet in the solar system.
Earth is the third planet in the solar system.
Command tail
will print the last NUM lines, or 10 if the -n
switch
is omitted.
[learner number]$ cd ../planets
[learner planets]$ tail -n 3 earth.txt
Earth is the third planet in the solar system.
The highest point found on Earth is Mount Everest.
70% of the Earth’s surface is covered by water.
We can follow the output of any file (to see live output) by passing the
-f
switch to tail
.