How to use the command 'head' (with examples)
- Osx
- December 25, 2023
The ‘head’ command is used to output the first part of a file or multiple files. It allows you to specify how many lines or bytes you want to display from the beginning of the file. This command is useful for quickly previewing the contents of a file without having to open it in an editor.
Use case 1: Output the first few lines of a file
Code:
head --lines 8 path/to/file
Motivation: You might want to quickly view the first few lines of a large log file to get an overview of its contents without having to load the entire file into an editor.
Explanation:
- head: This is the command itself.
- –lines 8: This argument tells head to display the first 8 lines of the file.
- path/to/file: This is the path to the file you want to view.
Example output:
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Use case 2: Output the first few bytes of a file
Code:
head --bytes 8 path/to/file
Motivation: You might have a binary file and want to view the beginning of it to check the file format or header information.
Explanation:
- head: This is the command itself.
- –bytes 8: This argument tells head to display the first 8 bytes of the file.
- path/to/file: This is the path to the file you want to view.
Example output:
01010101
Use case 3: Output everything but the last few lines of a file
Code:
head --lines -8 path/to/file
Motivation: You might want to exclude the last few lines of a log file when analyzing its contents. For example, if the last few lines contain irrelevant information or are not yet complete.
Explanation:
- head: This is the command itself.
- –lines -8: This argument tells head to display everything except the last 8 lines of the file.
- path/to/file: This is the path to the file you want to view.
Example output:
Line 1
Line 2
Line 3
Line 4
Line 5
Use case 4: Output everything but the last few bytes of a file
Code:
head --bytes -8 path/to/file
Motivation: You might have a binary file and want to exclude the last few bytes when analyzing it. For example, if the last few bytes are checksum or metadata that you’re not interested in.
Explanation:
- head: This is the command itself.
- –bytes -8: This argument tells head to display everything except the last 8 bytes of the file.
- path/to/file: This is the path to the file you want to view.
Example output:
01010101
01010101
01010101
01010101
Conclusion:
The ‘head’ command is a handy tool for quickly previewing the beginning of files. Whether you need to inspect the first few lines or bytes, or exclude the last few lines or bytes, ‘head’ provides a simple and efficient solution.