O'Reilly logo

Linux Shell Scripting Cookbook by Sarath Lakshman

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

head and tail – 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 like 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 also need to print the first n lines or last n lines. Also we may need to print all the lines except the last "n" lines or all lines except first "n" lines.

Another use case is to print lines from n-th to m-th 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 first 10 lines as follows:

$ head file

Read the data from stdin as follows:

$ cat text | head

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required