In the Linux system, sometimes we need to perform precise operations on text files, such as deleting the last line of the file. This article explains how to use command line tools to achieve this, including specific code examples.
First of all, we need to use a powerful and flexible text processing tool-sed
. sed
is a stream editor that can process and edit text on the command line. We can use the sed
command to delete the last line of the file.
Suppose we have a text file example.txt
, which contains multiple lines of text content. We want to delete the last line of the file. We can use the following command to achieve this:
sed -i '$d' example.txt
Let us explain this command in detail:
sed
: means calling sed
Order. -i
: Indicates making modifications directly on the original file instead of displaying the results on the screen. $d
: This is a command of sed
, $
means the last line, d
means to delete the line. After executing this command, the last line of the example.txt
file will be deleted. It should be noted that this will directly modify the original file, so be sure to back up the file contents before operation.
If we want to delete the second to last line, we can modify it slightly:
sed -i '$-1d' example.txt
In this command, $-1
represents the second to last line. After execution, the penultimate line of the example.txt
file will be deleted.
In addition to using the sed
command, we can also combine it with other commands to delete the line at the end of the file. For example, we can use the head
command combined with output redirection to achieve:
head -n -1 example.txt > temp.txt mv temp.txt example.txt
The head -n -1
here means displaying the file content except the last line. , and then redirect the results to a temporary file temp.txt
. Finally, rename temp.txt
to example.txt
to delete the line at the end of the file.
To sum up, through the sed
command or in combination with other commands, the precise deletion of the line at the end of the file can be easily achieved in the Linux system. These commands will be very useful tools when you need to modify text files. I hope this article helps you better understand and use these commands.
The above is the detailed content of Tutorial on accurately deleting lines at the end of files in Linux. For more information, please follow other related articles on the PHP Chinese website!