In [1]:
export LANGUAGE=en # Be sure the commands output English text
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.
The first reflex is to print the help (option --help
) :
In [2]:
head --help
We will create a dummy file with random content, from the dictionnary (/etc/dictionaries-common/words
):
In [3]:
cat /etc/dictionaries-common/words > /tmp/file.txt
Now we can print the first 10 lines of this file /tmp/file.txt
:
In [4]:
head /tmp/file.txt
If we want the first 20 lines, we use the option -n NUMBER
:
In [5]:
head -n 20 /tmp/file.txt
Let's count how many lines there is:
In [6]:
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:
In [7]:
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
The other command, tail
, works exactly like head
except the lines are counted from the end:
In [8]:
tail --help
In [9]:
tail /tmp/file.txt # Last 10 lines
In [10]:
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
) :
In [14]:
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!