Home > Article > Operation and Maintenance > Linux file operation tips: delete multiple lines at the end
When using the Linux operating system for file processing, you often encounter situations where you need to delete multiple lines at the end of the file. This operation can usually be achieved through some simple commands. The following will introduce some common Linux file operation techniques and provide specific code examples.
The sed command is a stream editor that can be used to process text. By combining the sed command and regular expressions, you can easily delete multiple lines at the end of the file.
The specific code is as follows:
sed -i '$d' file.txt
In this command, -i
means directly modifying the file content, $
means matching the last line of the file, d
means to delete the matching lines. After executing this command, the line at the end of file file.txt
will be deleted.
If you need to delete multiple lines at the end, you can use the following command:
sed -i '{start_line_number},{end_line_number}d' file.txt
where {start_line_number}
is the starting line number that needs to be deleted from the end. {end_line_number}
is the end line number to be deleted. After executing this command, the contents from the starting line to the ending line in the file file.txt
will be deleted.
The head command is usually used to display the header content of the file, but it can also be combined with -n
Parameter to choose to display the first few lines of the file.
The specific code is as follows:
head -n -$N file.txt > temp.txt && mv temp.txt file.txt
where $N
represents the number of rows that need to be deleted. In this command, head -n -$N file.txt
will output the contents of the file except the last N lines to the temp.txt
temporary file, and then pass ## The #mv command renames the temporary file to the original file name
file.txt, thereby achieving the effect of deleting multiple lines at the end.
The above is the detailed content of Linux file operation tips: delete multiple lines at the end. For more information, please follow other related articles on the PHP Chinese website!