Lesson 24: head Command
In this lesson, you'll learn how to use the head command to display the first few lines of a file in Linux.
head Command: A simple utility used to display the first few lines of a file or output.The head command reads the first ten lines of any given file name.
head Command Syntax
The syntax of the head command is very simple and it is identical to other Linux commands:
$ head [OPTIONS] [FILE-1] [FILE-2] ...
It is important to note that, in the above syntax, both OPTIONS and FILE parameters are optional.
So, if the input file is not provided or the file argument is a hyphen (-), then it reads the input from the stdin stream.
head Command Options
| Option | Description |
|---|---|
-n N |
Display the first N lines of the file |
-n -N |
Display all lines except the last N lines |
-c N |
Display the first N bytes of the file |
-c -N |
Display all bytes except the last N bytes |
-v |
Always display the filename as a header |
-q |
Suppress the filename header when using multiple files |
To start, first let's create a simple text file with the following contents:
$ cat file-1.txt
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Line 11
Line 12
Now, the input file is ready. So let's use it to demonstrate the usage of the head command.
1. Show the First 10 Lines of a File
By default, the head command displays the first ten lines of the input file as shown.
$ head file-1.txt
Line 1
Line 2
Line 3
Line 4
Line 5
Line 6
Line 7
Line 8
Line 9
Line 10
Here, we can see that the command shows only the first ten lines of the file-1.txt file.
2. Show First N Lines of a File
In the previous example, we saw that the head command displays the first ten lines of the file by default. However, we can overwrite this default behavior using the -n option, which allows us to limit the number of lines to be displayed.
To understand this, let's use the command below to display the first five lines of the file-1.txt file:
$ head -n 5 file-1.txt
Line 1
Line 2
Line 3
Line 4
Line 5