Linux has a set of powerful commands for doing different operations. Among those commands is the Head. It is also an important command that use to display the N numbers of lines of a file. Why is it needed? Imagine a scenario where you are working on the Linux command line, and continuously a log file is being built or getting updated.
Your need is only to view the first few lines to make sure things are working as intended. That’s when the Head command will be handy as it can quickly show only the first few lines of the file.
Syntax:
head <option> <file>
Where <option> are different parameters that can be used with the head command for various purposes.
Head Command in Linux Examples
1. Display the first ten lines
By default, it returns the first ten lines of the file. If more than one filename is provided, then it returns the first ten lines of each file.
head /etc/passwd
Example:
2. Display the first N lines
Instead of displaying the first ten lines, you can control the number of lines you want to show. The general syntax for such a purpose is as follows:
head -n <num> <file>
Where <num> is a mandatory parameter that represents the number of lines you wish to show in the output.
head -n 5 /etc/passwd
Example:
3. Display the first N bytes
You can also define the number of first bytes you want to show in the output instead of lines.
Syntax:
head -c <num> <file>
Where <num> is a mandatory parameter that represents the number of bytes you want to display in the output.
head -c 50 /etc/passwd
Example:
4. Display file data with Header
We can use the head command to display lines from multiple files always preceded by filename header.
Syntax:
head -v <file1> <file2> head -v /etc/passwd /etc/shadow
Example:
5. Display file data without Header
We can use the head command to display lines from multiple files without preceded by filename header.
Syntax:
head -q <file1> <file2> head -q /etc/passwd /etc/shadow
Example:
6. Filter file data using the grep command
You can filter data from the file by combining the grep command with the head command using a pipe.
Syntax:
head <file> | grep <searchterm>
Here <searchterm> is the string you want to search and display within the file.
head /var/log/auth.log | grep tuts
This command will only return lines containing our search term ‘tuts’.
Example:
7. Display N most recently used files
Head command can be combined using a pipe with other Linux commands. Like you can use the head command with ls command to get N most recent used files.
Syntax:
ls -t | head -n 5
This command will first find the most recent files and will display only the top 5 most recently used files.
Example:
Conclusion
As you can see, the head command is handy for manipulating large files, especially the vast log files where you want to see recent data instead of opening up a complete file, which may consume a lot of memory and time.