How to Use the head Command in Linux?


Understanding the head Command in Linux

The head command is a powerful utility in Linux and Unix-like operating systems that allows users to view the beginning of files. It’s particularly useful for quickly checking the contents of large files without opening the entire document. Here’s a detailed look at how to leverage this command effectively.

Basic Usage

The primary purpose of the head command is to output the first few lines or bytes of a file. The default behavior displays the first 10 lines, but you can customize this as needed.

Output the First Few Lines of a File

To display the first few lines of a file, use the following syntax:

head [-n|--lines] count path/to/file

For example, to display the first 5 lines of a file named example.txt, you would execute:

head -n 5 example.txt

This command is helpful for quickly grasping the structure or the beginning context of a file.

Output the First Few Bytes of a File

You can also retrieve the first few bytes instead of lines by using the -c option:

head [-c|--bytes] count path/to/file

For instance, to get the first 20 bytes of example.txt, use:

head -c 20 example.txt

This can be particularly useful for binary files or for quickly checking file headers.

Advanced Usage

The head command can also be used to output everything but the last few lines or bytes of a file. This is useful when you want to exclude specific sections of a file from your view.

Exclude Last Few Lines

To show everything except the last few lines:

head [-n|--lines] -count path/to/file

For example, to display all but the last 3 lines of example.txt:

head -n -3 example.txt

Exclude Last Few Bytes

Similarly, to output everything but the last few bytes, use:

head [-c|--bytes] -count path/to/file

For instance, to show all but the last 10 bytes of example.txt:

head -c -10 example.txt

Conclusion

The head command is an essential tool for any Linux user looking to manipulate and view file content efficiently. By mastering this command, you can easily navigate large files and extract relevant information quickly.

For more detailed information about the head command and its options, check the GNU Coreutils manual here.

See Also