Saving the Output of tail
and head
Commands to a New File
In the Linux operating system, the tail
and head
commands are commonly used to display the last or first few lines of a file, respectively. However, there may be times when you need to save the output of these commands to a new file for further processing or analysis. Here's how you can do it:
Using Redirection Operators
The most straightforward way to save the output of tail
and head
commands to a new file is by using the redirection operators >
and >>
. The >
operator overwrites the contents of the target file, while the >>
operator appends the output to the end of the target file.
-
Saving the output of
tail
to a new file:tail -n 5 file.txt > new_file.txt
This command will save the last 5 lines of
file.txt
to a new file callednew_file.txt
. -
Saving the output of
head
to a new file:head -n 3 file.txt > new_file.txt
This command will save the first 3 lines of
file.txt
to a new file callednew_file.txt
. -
Appending the output of
tail
to an existing file:tail -n 10 file.txt >> existing_file.txt
This command will append the last 10 lines of
file.txt
to the end ofexisting_file.txt
.
Using Pipes
Alternatively, you can use the pipe |
operator to chain the tail
or head
command with the cat
command, which will write the output to a new file.
-
Saving the output of
tail
to a new file:tail -n 5 file.txt | cat > new_file.txt
This command will save the last 5 lines of
file.txt
to a new file callednew_file.txt
. -
Saving the output of
head
to a new file:head -n 3 file.txt | cat > new_file.txt
This command will save the first 3 lines of
file.txt
to a new file callednew_file.txt
.
Visualizing the Concepts
Here's a Mermaid diagram that illustrates the concepts of using redirection operators and pipes to save the output of tail
and head
commands to a new file:
The diagram shows that you can either use the redirection operators >
or >>
to save the output of tail
or head
commands directly to a new file, or you can use the pipe |
operator to chain the tail
or head
command with the cat
command, which will then write the output to a new file.
By using these techniques, you can easily save the output of tail
and head
commands to a new file for further processing or analysis, making your Linux workflow more efficient and streamlined.