This tutorial explains Linux “head” command, options and its usage with examples.
Usage:
head [OPTION]… [FILE]…
Head prints the first N number of data of the given input. By default, it prints first 10 lines of each given file.
It can be used for Viewing Huge Log Files in Unix.
Here’s the listing of example usage of “head” command:
Here we will be using file sample.txt as a example.
sanfoundry-> cat sample.txt Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8 Line 9 Line 10 Line 11 Line 12
1. To print the first N number of lines(head -n num file_path):
sanfoundry-> head -n 6 sample.txt Line 1 Line 2 Line 3 Line 4 Line 5 Line 6
When you simply pass the file name as an argument to head, it prints out the first 10 lines of the file.
2. To print N number of lines by specifying N (head -num file_path):
sanfoundry-> head -6 sample.txt Line 1 Line 2 Line 3 Line 4 Line 5 Line 6
3. To print the N number of bytes(head -c num_of_bytes file_path):
With “-c” option you can see contents of BYTES=num_of_bytes from the start of file.
sanfoundry-> head -c 13 sample.txt Line 1 Line 2
4. To ignore last N lines of a file using head command(head -n -num file_path):
sanfoundry-> head -n -5 sample.txt Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7
Here you can see that last 5 lines of file sample.txt are ignored.
5. To skip printing last n bytes(head -c -num_of_bytes_to_skip file_path):
sanfoundry-> head -c -30 sample.txt Line 1 Line 2 Line 3 Line 4 Line 5 Line 6 Line 7 Line 8
Here last 30 bytes from the file sample.txt are skipped and rest of the file is printed.
6. To print header information always(head -v file_path) :
sanfoundry-> head -v sample.txt ==> sample.txt <== Line 1 Line 2 Line 3 Line 4 Line 5 ....
7. To pass Output of one command as Input to head command:
sanfoundry-> ls | head 1.c 1.txt 2.c animation.py a.out Backups bus_0.zip collisionDetection.py C_Programming Desktop
8. To print line between M and N lines:
For this purpose you can use head -M file_path | tail -(M-N) command, Since first line takes first M lines and tail command cuts last (M-N)Lines.
sanfoundry-> head -10 sample.txt | tail -3 Line 8 Line 9 Line 10
Sanfoundry Global Education & Learning Series – 1000 Linux Tutorials.
- Check Information Technology Books
- Apply for Programming Internship
- Check Linux Books
- Practice Programming MCQs