head
Command in Linux
Summary
The head
command is a simple yet powerful utility in Linux used to display the beginning of a file or piped input. By default, it shows the first 10 lines, but this can be customized to display any number of lines or even bytes.
Introduction
The head
command is a fundamental tool for quickly inspecting the content of files without opening them in a text editor. It's particularly useful for examining log files, configuration files, or any other text-based data where the initial lines provide valuable information. Its simplicity and ability to work with piped input make it a versatile tool in shell scripting and command-line workflows.
Use Case and Examples
Display the first 10 lines of a file
This command will output the first 10 lines of the file namedmyfile.txt
. Display the first 20 lines of a file
This command will output the first 20 lines of the file namedmyfile.txt
. The -n
flag allows you to specify the number of lines to display. Display the first 500 bytes of a file
This command will display the first 500 bytes of the filemyfile.txt
. The -c
flag allows you to specify the number of bytes to display. Display the first 3 lines of output from another command
This command pipes the output ofls -l
(a long listing of files and directories) to head
, which then displays the first 3 lines of the listing. Display the first 10 lines of multiple files
This command displays the first 10 lines offile1.txt
, file2.txt
, and file3.txt
sequentially, with each file's name preceding its output. Commonly used flags
Flag | Description | Example |
---|---|---|
-n or --lines=K | Specifies the number of lines to display. K represents the number of lines. | head -n 5 myfile.txt (Displays the first 5 lines) |
-c or --bytes=K | Specifies the number of bytes to display. K represents the number of bytes. | head -c 100 myfile.txt (Displays the first 100 bytes) |
-q or --quiet or --silent | Suppresses printing of headers when multiple files are specified. | head -q file1.txt file2.txt (Displays content without file name headers) |
-v or --verbose | Always print headers giving file names. | head -v file1.txt (Displays content with file name header, even if only one file is given) |