Linux head command

Updated: 05/04/2019 by Computer Hope
head command

On Unix-like operating systems, the head command outputs the first part (the head) of a file or files.

This page covers the GNU/Linux version of head.

Description

head, by default, prints the first 10 lines of each FILE to standard output. With more than one FILE, it precedes each set of output with a header identifying the file name. If no FILE is specified, or when FILE is specified as a dash ("-"), head reads from standard input.

Syntax

head [OPTION]... [FILE]...

Options

-c, --bytes=[-]num Print the first num bytes of each file; with a 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 identifying file names.
-v, --verbose Always print headers identifying file names.
--help Display a help message and exit.
--version Output version information and exit.

In the above options, num may have a multiplier suffix:

b 512
kB 1000
K 1024
MB 1000*1000
M 1024*1024
GB 1000*1000*1000
G 1024*1024*1024

...and so on for T, P, E, Z, Y.

Examples

head myfile.txt

Display the first ten lines of myfile.txt.

head -15 myfile.txt

Display the first fifteen lines of myfile.txt.

head myfile.txt myfile2.txt

Display the first ten lines of both myfile.txt and myfile2.txt, with a header before each that indicates the file name.

head -n 5 myfile.txt myfile2.txt

Displays only the first 5 lines of both files.

head -c 20 myfile.txt

Will output only the first twenty bytes (characters) of myfile.txt. Newlines count as a single character, so if head prints out a newline, it will count it as a byte.

head -n 5K myfile.txt

Displays the first 5,000 lines of myfile.txt.

head -c 6M myfile.txt

Displays the first six megabytes.

head -

If a dash is specified for the file name, head reads from standard input rather than a regular file.

head myfile.txt myfile2.txt -

Display the first ten lines of myfile.txt, myfile2.txt, and standard input.

head -n 4 *.txt

Display the first four lines of every file in the working directory whose file name ends in the extension .txt.

head -n 4 -q *.txt

Same as the previous command, but uses quiet (-q) output, which will not print a header before the lines of each file.

cat — Output the contents of a file.
more — Display text one screen at a time.
pg — Browse page by page through text files.
tail — Print the last lines of a text file.