How to delete specific lines of data from a file in Linux?
In Linux, you can use the following command to delete specific lines of data from a file.
- sed is a stream editor commonly used for parsing and transforming text.
sed -i '<行号>d' 文件名
In this case,
sed -i '5d' file.txt
- search
grep -v '<行内容>' 文件名 > 临时文件名 && mv 临时文件名 文件名
In this command, <行内容> represents the content of the line to be deleted, file name is the name of the file to be operated on, and temporary file name is a temporary file name. For example, to delete a line in the file file.txt that contains the string “hello”, you can use the following command:
grep -v 'hello' file.txt > temp.txt && mv temp.txt file.txt
This command will create a temporary file called temp.txt, write the lines that do not contain “hello” into it, and then rename the temporary file as the original file name file.txt.
Please remember to back up your files before using these commands to delete data, in order to avoid accidental deletion or modification.