How to quickly delete the line at the end of a file in Linux

WBOY
Release: 2024-03-01 21:36:04
Original
1032 people have browsed it

How to quickly delete the line at the end of a file in Linux

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
Copy after login

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
Copy after login

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
Copy after login

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 the

cat 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
Copy after login
Through the above steps, you can quickly delete the last line of the file under the Linux system. In practical applications, these commands can quickly and easily handle the deletion of lines at the end of the file.

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!