Linux has several commands that helps to display the contents of a file. such as:
cat commandnl commandBut 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.
Syntax:
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 1line 2line 3line 4line 5line 6line 7line 8line 9line 10line 11line 12line 13line 14line 15line 16line 17line 18line 19line 20line 21line 22line 23line 24line 25
By default the head command prints the first 10 lines of the file without any option.
~$ head file.txt line 1line 2line 3line 4line 5line 6line 7line 8line 9line 10
2. Display content of Multiple files
~$ head file.txt file1.txt ==> file.txt <==line 1line 2line 3line 4line 5line 6line 7line 8line 9line 10==> file1.txt <==line 1line 2line 3line 4line 5line 6line 7line 8line 9line 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.
Syntax:
head -n [Number] [Filename]
[Number]
- Specify the number of lines you want to print.[Filename]
- Specify the FilenameLet's take some examples.
Ex. # 1 - List first 7 lines.
~$ head -n 7 file.txt line 1line 2line 3line 4line 5line 6line 7
Ex. # 2 - List first 3 lines.
~$ head -n 3 file.txt line 1line 2line 3
Ex. # 3 - List first 5 lines (Using long option).
~$ head --lines=5 file.txt line 1line 2line 3line 4line 5
Bonus Tip:
You can avoid using the -n option with the head command.
Example:
~$ head -5 file.txt
Read Complete Story