When processing files under Linux system, sometimes it is necessary to delete the lines at the end of the file. This operation is very common in practical applications and can be achieved through some simple commands. This article will introduce the steps to quickly delete the line at the end of the file in Linux system, and provide specific code examples.
Step 1: Check the last line of the file
Before performing the deletion operation, you first need to confirm which line is the last line of the file. You can use the tail
command to view the last line of the file. The specific command is as follows:
tail -n 1 filename
Among them, filename
represents the file name to be operated, -n 1
means only viewing the content of the last line.
Step 2: Delete the last line of the file
Generally, you can use the sed
command to delete the last line of the file. The specific commands are as follows:
sed -i '$d' filename
Among them, -i
means to modify directly on the original file, and '$d'
means to delete the last line.
In addition, you can also use the combination of head
and tempfile
to delete the line at the end of the file. The specific commands are as follows:
head -n $(($(wc -l < filename) - 1)) filename > tempfile && mv tempfile filename
Among the above commands, wc -l < filename
is used to calculate the total number of lines in the file, and then passes head
and tempfile# The combination of ## deletes the last line.
Step 3: Verify the deletion operation
After the deletion operation is completed, you can use thecat command to view the contents of the file to ensure that the last line has been Successfully deleted. The specific command is as follows:
cat filename
The above is the detailed content of How to quickly delete the line at the end of a file in Linux. For more information, please follow other related articles on the PHP Chinese website!