Table of Contents
head command outputs the first part of the files on standard output. This is very useful and frequently used command for processing data from files. All the Linux CLI and shell scripting users must have good understanding of
head command in Linux.
The default head command prints first 10 lines of each FILE to standard output. For more than one file, print filename with each FILE output.
This tutorial describes you to use of head command in Linux system. Also, provide you some basic examples of head command with explanations.
A basic syntax of head command is like:
head [OPTION]... [FILE]...
Here you can specify different options followed by one or multiple files.
Using head Command in Linux
Open a terminal on your system and type head followed by the input file name. For this tutorial, we are using a sample file contains list of employees details.
This will print top 10 lines from the
employee.txt file on standard output.
The default head command prints 10 lines, which can be override by passing the command line options.
Specify Number of Lines
--lines command line option to specify number of lines to display on standard output.
You can also use
- just before numbers to print all but the last NUM lines of each file.
- Display all lines except last 10 lines from file:
head -n -10 employee.txt
Display Output by Size
--bytes to print specified number of bytes of beginning of the each file.
For example, to print first 100 bytes from emplyee.txt, type:
head -c 100 employee.txt
The size can also specify with a multiplier suffix, like:
- 1b = 1 x 512
- 1kB = 1 x 1000
- 1K = 1 x 1024
- 1MB = 1 x 1000 x 1000
- 1M = 1 x 1024 x 1024
- 1GB = 1 x 1000 x 1000 x 1000
- 1G = 1 x 1024 x 1024 x 1024
- and so on for T, P, E, Z, Y etc
similarly, run more examples with differnt-2 sizes and see the result on screen.
head -c 1b employee.txt
#Prints first 512 bytes
head -c 1kB employee.txt
#Prints first 1000 bytes
head -c 1K employee.txt
#Prints first 1024 bytes
Using head with pipeline (|)
You can also use head to print specific number of lines from output of another command.
In the following, the head command will print first 5 lines from the output of cat command.
cat employee.txt | head -n 5
Print lines between X and Y lines
We can also print lines from a file between two line numbers.
For example, you need to print only line numbers 6-10. Which means the output will skip top 1-5 lines and 11th to EOF.
cat employee.txt | head -n 10 | tail -n 5
This tutorial explained you to how to use Linux head command with useful examples. Hopefully, you will have bit understanding of head command in Linux.
Hope this helps!