Linux has several commands that helps to display the contents of a file. such as:
But these commands prints the entire contents of the file.
If the content of the file is too long, we have to read the whole file to see what we required.
And if there is a command that shows us as much content as we need, it becomes easier to work.
For Example, when we check the log of any Server or application, and we have to review some of the opening lines, it makes no sense for us to display the entire contents.
In such a Scenario, the head command can be used.
What is the use of Head Command?
Head command helps to display the first part of the files.
By default, it prints the first ten lines of a file, but you can display as many lines as you want using its other features.
In this article, I will teach you about the complete features of head command.
You must follow the syntax given below to use the head command.
head [OPTION]... [FILE]...
1. Display first ten lines of a File
Here I have a file named file.txt which contains some content.
Let’s try to understand the concept of the head command using this file.
~$ cat file.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 line 13 line 14 line 15 line 16 line 17 line 18 line 19 line 20 line 21 line 22 line 23 line 24 line 25
By default the head command prints the first 10 lines of the file without any option.
~$ head file.txt line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10
2. Display content of Multiple files
~$ head file.txt file1.txt ==> file.txt <== line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10 ==> file1.txt <== line 1 line 2 line 3 line 4 line 5 line 6 line 7 line 8 line 9 line 10
You can display the contents of several files. To do this, pass the path of files to head command separated by space.
Refer to the following example. Here I am listing the contents of file.txt and file1.txt
3. Print specified Lines
You can print as many lines as you want instead of the first ten lines.
For that, you have to pass the -n option to head command.
head -n [Number] [Filename]
[Number]- Specify the number of lines you want to print.
[Filename]- Specify the Filename
Let's take some examples.
Ex. # 1 - List first 7 lines.
~$ head -n 7 file.txt line 1 line 2 line 3 line 4 line 5 line 6 line 7
Ex. # 2 - List first 3 lines.
~$ head -n 3 file.txt line 1 line 2 line 3
Ex. # 3 - List first 5 lines (Using long option).
~$ head --lines=5 file.txt line 1 line 2 line 3 line 4 line 5
You can avoid using the -n option with the head command.
~$ head -5 file.txt