export LANGUAGE=en # Be sure the commands output English text
head
and tail
¶This short tutorial will show you how to use the linux command line tools head
and tail
, to respectively print the first lines and last lines of a file.
head
¶The first reflex is to print the help (option --help
) :
head --help
We will create a dummy file with random content, from the dictionnary (/etc/dictionaries-common/words
):
cat /etc/dictionaries-common/words > /tmp/file.txt
Now we can print the first 10 lines of this file /tmp/file.txt
:
head /tmp/file.txt
If we want the first 20 lines, we use the option -n NUMBER
:
head -n 20 /tmp/file.txt
Let's count how many lines there is:
wc -l /tmp/file.txt
That's a lot! Imagine we want to see all the file except the last 100 lines, we can use head
with a negative value for NUMBER
in the -n NUMBER
option:
head -n 100 /tmp/file.txt | wc -l # 100 lines, from 1st to 100th
head -n -100 /tmp/file.txt | wc -l # All lines but the last 100 lines, from 1st to 99071th
tail
¶The other command, tail
, works exactly like head
except the lines are counted from the end:
tail --help
tail /tmp/file.txt # Last 10 lines
tail -n 20 /tmp/file.txt # Last 20 lines
The option -n NUMBER
has the same behavior, except that it uses -n +NUMBER
to ask for all lines but the first NUMBER
(where head
was asking -n -NUMBER
) :
tail -n 100 /tmp/file.txt | wc -l # 100 lines, from 99071th to 99171th
tail -n +101 /tmp/file.txt | wc -l # All lines from line 101, from 101th to 99171th
That's all for today, folks!