head
The head
command in Unix and Linux is used to display the beginning of a file or piped data. By default, it shows the first 10 lines of each file it processes, but you can customize the number of lines or bytes displayed.
Basic Usage
The basic syntax for the head
command is:
options
: Command-line options to control the behavior ofhead
.file
: The file(s) to be processed. If no file is specified,head
reads from standard input.
Examples
Displaying the First 10 Lines of a File
To display the first 10 lines of a file:
Displaying a Custom Number of Lines
To display the first n
lines of a file, use the -n
option followed by the number of lines:
This command displays the first 5 lines of file.txt
.
Displaying a Custom Number of Bytes
To display the first n
bytes of a file, use the -c
option followed by the number of bytes:
This command displays the first 20 bytes of file.txt
.
Displaying Multiple Files
To display the first 10 lines of multiple files:
Output:
Piping Output to head
head
You can pipe the output of other commands into head
to view the first few lines of the output:
This command displays the first 10 lines of the ls -l
output.
Options
-n
Option: Number of Lines
-n
Option: Number of LinesTo specify the number of lines to display:
This command displays the first 15 lines of file.txt
.
-c
Option: Number of Bytes
-c
Option: Number of BytesTo specify the number of bytes to display:
This command displays the first 50 bytes of file.txt
.
-v
Option: Always Print Headers
-v
Option: Always Print HeadersTo always print headers when multiple files are provided, use the -v
option:
This command ensures that headers are printed even if only one file is processed.
-q
Option: Never Print Headers
-q
Option: Never Print HeadersTo suppress headers when multiple files are provided, use the -q
option:
This command prevents headers from being printed for each file.
Practical Use Cases
Previewing Files
When you want to quickly preview the beginning of a file, head
provides a convenient way to do so without opening the entire file in an editor.
Monitoring Log Files
When analyzing log files, you can use head
to view the most recent entries (especially in combination with tail
).
Debugging Scripts
When debugging scripts that produce a large amount of output, you can pipe the output to head
to see only the initial part of the output for quick analysis.
Summary
The head
command is a simple yet powerful utility for viewing the beginning of files or piped data in Unix and Linux environments. Its flexibility in displaying a custom number of lines or bytes, combined with its ability to handle multiple files, makes it an essential tool for file and data inspection.
help
man
NAME head - output the first part of files
SYNOPSIS head [OPTION]... [FILE]...
DESCRIPTION Print the first 10 lines of each FILE to standard output. With more than one FILE, pre‐ cede each with a header giving the file name.
Last updated