Site icon DesignLinux

Linux Head Command

Linux Head Command

The head command is used to print the few first lines (by default 10 lines) of file or standard output. This tutorial shows you how to use the Linux head command with practical examples.

Head Command Syntax

Below is the basic syntax for the head command:

head [OPTION]... [FILE]...

Here,

Use of Head Command

When you used head command without any option it will show the first 10 lines by default like below:

head filename

Display a Specific Number of Lines

To display the specific the number of lines, use the -n (--lines) option followed by the integer number.

head -n  filename

For example, to show the first 25 lines from a file readme.md, you would run:

head -n 25 readme.md

Another way is, you can remove the n and just use the hyphen (-) and the number without space between them.

Below command will give the same output as the previous example:

head -25 readme.md

Show Specific Number of Bytes

Use the -c (--bytes) option to display a specific number of bytes:

head -c  filename

For instance, to print the first 150 bytes of data of a file readme.md, run:

head -c 150 readme.md

You also can use the multiplier to specify the number of bytes. b multiplies it by 512, kB multiplies it by 1000, K multiplies it by 1024, MB multiplies it by 1000000, M multiplies it by 1048576, and so on.

In following example, it will show the first 3 kilobytes of the file readme.md:

head -c 5k readme.md

Display Multiple Files

When the multiple files are given with the head command, it will display the first 10 lines of each files.

head filename1 filename2

You can use the same options as a single file. For example to show the first 15 lines of the files readme.md and license.txt:

head -n 15 readme.md license.txt

If multiple files given then each file name is showing as header in output.

Use Head with Other Commands

The head command can be piped with other commands by redirecting the standard output from other commands.

In the following example, the output of the ls command is piped to head to show only the three most recently modified files or folders.

ls -t | head -n 3
about.php
contact.php
index.php

Conclusion

This guide shown you how to use the Head command in Linux with different options.

If you have any question or feedback, feel free to leave a comment below.

Exit mobile version