How to display the first part of the file in the Linux system?


To display the first part of the file, we use the head command in the Linux system.

The head command is used to display the beginning of a text file or piped data. By default, it displays the first ten lines of the specified files. The tail command is also used to display the ending part of the file.

Syntax

The general syntax of the head command is as follow −

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

Brief description of options available in the head command.

Sr.No.
Option & Description
1
-c, --byte = [-]NUM
Display the first NUM bytes of each file. With the leading ‘-‘, print all but the last NUM bytes of each file.
2
-n, --lines [-]NUM
Display the first NUM lines instead of the first ten with the leading ‘- ‘, display all but the last NUM lines of each file.
3
-q, --quiet, --silent
Never prompt headers giving file names.
4
-v, --verbose
Always display headers giving file names.
5
-z, --zero-terminated
Line delimiter is NULL, not newline.
6
--help
Displays a help message and then exits.
7
--version
It gives info about the version and then exits.

By default, the head command prints the first ten lines without any option as shown in this example.

First, we will create a file containing more than ten lines using the cat command in the Linux system as shown below.

$ cat >text.txt
First line...
Second line...
Third line...
Fourth line...
Fifth line...
Sixth line...
Seventh line...
Eighth line...Ninth line...
Tenth line...
Eleventh line...

Then, we will use the head command in the Linux system to display the first ten lines.

$ head text.txt
First line...
Second line...
Third line...
Fourth line...
Fifth line...
Sixth line...
Seventh line...
Eighth line...
Ninth line...
Tenth line...

To print the first n lines, we use the -n or --lines option with the head command as shown below.

Suppose we want to display four lines of the text.txt file then we have to execute the command as shown below.

$ head -n 4 text.txt

To print lines between m and n, we use the head and tail command in the Linux system as shown below.

Suppose we want to display lines between 7 to 9 of the text.txt file then we have to execute the command as shown below.

$ head -n 7 text.txt | tail -9

Note – The tail command is used to prints lines from last in the Linux system.

To check more information about the head command, we use the --help option with the head command in the Linux operating system as shown below.

$ head --help

To check version information of the head command, we use the --version option with the head command in the Linux operating system as shown below. $ head --version

Updated on: 01-Jul-2021

11K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements