Using head command in Linux


Linux head command prints the first given number of lines by default 10 lines of a file provided as input on the standard output. It is complementary to the Linux tail command which prints the given number of lines from the bottom of a file.

In this article, you will see the usage of the Linux head command along with some examples.

How to use the head command in Linux

The syntax of how to use a head command on a Linux system is given below.

head [option].. [file]

Where you can find a list of options that can be used with the head command on the man page of head command. And you can enter one or more files as input to this command.

Examples of Linux head command

Let’s say we have a file distro.txt, you can see the content of this file which is given below.

Now when you run the given command by default it will print the 10 lines from the given file.

head filename.txt

For example –

head distro.txt

The first 10 lines of distro.txt will be printed you can see these in the image below –

How to display a specific number of lines

To display a specific number of lines of a file you need to use option -n or --lines with the head command. For example to display the first 5 lines of file distro.txt use –

head -n 5 distro.txt

alternatively, you can use –

head -5 distro.txt

Both of the given commands will print the same output. You can see the output in the given image –

How to display a specific number of bytes

You can display the specified number of bytes from a file you need to use the option -c or --bytes with the head command. For example to display 50 bytes of the file distro.txt use –

head -c 50 distro.txt

You can see the output below –

How to display the content of multiple files

You provide more than one file as input to head command by default it will display the 10 lines of each file. For example, if there are two files then it will print the first 10 lines from the first file and the first 10 lines from the second file.

For example –

head file1.txt file2.txt

Similarly, you can use the other available options with the head command. This command can be used with other commands using pipes.

Conclusion

Ok, that’s all for now. if you have any query then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.