Using head and tail for printing the last or first 10 lines
When looking into a large file, which consists of thousands of lines, we will not use a command such as cat
to print the entire file contents. Instead we look for a sample (for example, the first 10 lines of the file or the last 10 lines of the file). We may need to print the first n lines or last n lines and even print all the lines except the last n lines or all lines except first n lines.
Another use case is to print lines from mth to nth lines.
The commands head
and tail
can help us do this.
How to do it...
The head
command always reads the header portion of the input file.
Print the first 10 lines as follows:
$ head file
Read the data from
stdin
as follows:$ cat text | head
Specify the number of first lines to be printed as follows:
$ head -n 4 file
This command prints four lines.
Print all lines excluding the last
M
lines as follows:$ head -n -M file
Note
Note that it is negative M.
For example, to print all the lines except the...