head - Linux
Overview
The head
command in Linux outputs the first part of files, allowing users to view the beginning of one or more files directly in the terminal. This command is primarily used to quickly view the initial segments of large files or to output the first few lines of data for processing in scripts or pipelines.
Syntax
The basic syntax of the head
command is:
head [OPTION]... [FILE]...
If no FILE is specified, or if FILE is -
, head
reads from standard input.
Options/Flags
-c, --bytes=[-]NUM
: Print the first NUM bytes of each file; with the leading ‘-‘, print all but the last NUM bytes of each file.-n, --lines=[-]NUM
: Print the first NUM lines instead of the first 10; with the leading ‘-‘, print all but the last NUM lines of each file.-q, --quiet, --silent
: Never print headers giving file names.-v, --verbose
: Always print headers giving file names.--help
: Display a help message and exit.--version
: Output version information and exit.
The default behavior of head
is to print the first 10 lines (-n 10
) of each file.
Examples
-
Basic Usage:
View the first 10 lines of a file:head filename.txt
-
Specify Number of Lines:
Display the first 20 lines of a file:head -n 20 filename.txt
-
Multiple Files:
Display the first 10 lines from each of two files:head file1.txt file2.txt
-
Bytes Instead of Lines:
Print the first 100 bytes of a file:head -c 100 filename.txt
-
Suppress Header Names:
When viewing multiple files, suppress the header that states the file name:head -n 5 file1.txt file2.txt --quiet
Common Issues
- File Not Found: If the file doesn’t exist,
head
will return an error. Ensure the file path is correct. - Binary Files: Using
head
to view binary files may produce garbled text in the terminal. It’s better used on text files.
Integration
head
is often combined with other commands in Unix-like operating systems for more complex tasks:
-
Piping with
grep
:grep 'searchTerm' largefile.txt | head -n 5
This example searches for ‘searchTerm’ in ‘largefile.txt’ and displays only the first 5 matches.
-
Combining
head
andtail
:head -n 20 file.txt | tail -n 10
This command sequence shows lines 11 to 20 of ‘file.txt’.
Related Commands
tail
: Outputs the last part of files.cat
: Concatenates and displays files.more
andless
: Tools for incremental file viewing.
For more details, please refer to the official documentation or the man pages (man head
).