How to Use the head and tail Commands for Text Processing on Linux
Linux users often work with large amounts of text data, and the head and tail commands are two of the most commonly used tools for processing this data. These commands allow you to quickly view the beginning or end of a file, or extract a specific section of text.
In this article, we will explore how to use the head and tail commands for text processing on Linux.
What are head and tail commands?
The head command is used to display the first few lines of a file, while the tail command is used to display the last few lines of a file. These commands are often used to quickly view the contents of a file without having to open it in a text editor.
How to use head command?
The basic syntax for the head command is as follows:
“`
head [OPTIONS] FILENAME
“`
Here are some of the most commonly used options:
– `-n N`: Display the first N lines of the file (default is 10).
– `-q`: Quiet mode, only displays the lines of the file.
– `-v`: Verbose mode, displays the name of the file before the lines.
Let’s look at some examples:
Display the first 5 lines of a file:
“`
head -n 5 FILENAME
“`
Display the first 10 lines of several files:
“`
head FILE1 FILE2 FILE3
“`
Display the first 5 lines of a file and indicate the name of the file:
“`
head -v -n 5 FILENAME
“`
How to use tail command?
The basic syntax for the tail command is as follows:
“`
tail [OPTIONS] FILENAME
“`
Here are some of the most commonly used options:
– `-n N`: Display the last N lines of the file (default is 10).
– `-q`: Quiet mode, only displays the lines of the file.
– `-v`: Verbose mode, displays the name of the file before the lines.
Let’s look at some examples:
Display the last 5 lines of a file:
“`
tail -n 5 FILENAME
“`
Display the last 10 lines of several files:
“`
tail FILE1 FILE2 FILE3
“`
Display the last 5 lines of a file and indicate the name of the file:
“`
tail -v -n 5 FILENAME
“`