How to Master the head Command in Linux


Mastering the head Command in Linux

The head command is a fundamental utility in Linux that allows users to quickly view the beginning portion of files. This can be incredibly useful for checking the contents of large files without having to open the entire document. In this post, we’ll explore how to efficiently use the head command with various options.

Output the First Part of Files

The primary function of the head command is to display the first few lines or bytes of a file. By default, it shows the first 10 lines, but you can customize the output as needed.

Basic Usage

Output the First Few Lines of a File

To view the first few lines of a file, you can use the following command:

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

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

head -n 5 example.txt

Output the First Few Bytes of a File

If you need to see the first few bytes of a file, the syntax is:

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

For instance, to display the first 10 bytes of a file, you can execute:

head -c 10 example.txt

Excluding the Last Few Lines and Bytes

Sometimes, you might want to see everything except the last part of a file.

Output Everything But the Last Few Lines

To show all but the last few lines of a file, you can use:

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

For example, to display everything except the last 3 lines of example.txt, use:

head -n -3 example.txt

Output Everything But the Last Few Bytes

Similarly, to exclude the last few bytes, you can run:

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

For instance, to see all but the last 10 bytes of example.txt, you would do:

head -c -10 example.txt

Conclusion

The head command is an essential tool for anyone using Linux, allowing for efficient navigation and display of large files. By mastering this command, you can quickly access relevant information without the need to open entire documents. For more detailed information about the head command and its options, be sure to check the GNU Coreutils manual.

Happy navigating!

See Also