The head
Command: Displaying the Beginning of a File
Summary
The head
command is a simple yet powerful utility used to display the beginning of a file, typically the first few lines. It's invaluable for quickly inspecting file contents without having to open the entire file.
Introduction
The head
command is a fundamental Linux utility designed to output the initial portion of a file to the standard output (usually your terminal). By default, it displays the first 10 lines of a file. However, you can customize the number of lines, or even bytes, to display using various options. head
is incredibly useful for previewing log files, configuration files, or any text-based data, making it a go-to tool for system administrators, developers, and anyone working with files on the command line.
Use case and Examples
Displaying the first 10 lines of a file
This command displays the first 10 lines of the filemyfile.txt
. Displaying the first 20 lines of a file
This command displays the first 20 lines of the filemyfile.txt
. The -n
option allows you to specify the number of lines to display. Displaying the first 5 lines of multiple files
This command displays the first 5 lines offile1.txt
, file2.txt
, and file3.txt
, with each file's name preceding its output. Displaying the first 100 bytes of a file
This command displays the first 100 bytes of the filemyfile.txt
. The -c
option allows you to specify the number of bytes to display. Piping output to head
ls -l
) and then pipes the output to head
, which displays the first 3 lines of the listing. Commonly used flags
Flag | Description | Example |
---|---|---|
-n , --lines=[NUMBER] | Specifies the number of lines to display. If NUMBER is preceded by a '+', it will print all lines starting from line NUMBER. | head -n 5 myfile.txt (displays the first 5 lines) head -n +15 myfile.txt (displays all lines starting from the 15th) |
-c , --bytes=[NUMBER] | Specifies the number of bytes to display. Can use suffixes like k (kilobytes), m (megabytes), g (gigabytes). | head -c 100 myfile.txt (displays the first 100 bytes) head -c 2k myfile.txt (displays the first 2 kilobytes) |
-q , --quiet , --silent | Suppresses printing of headers giving file names when multiple files are specified. | head -q file1.txt file2.txt (displays content without file name headers) |
-v , --verbose | Always print headers giving file names. | head -v file1.txt (displays content with file name header even for single file) |