How to remove lines containing a specific character in the shell?
Filter out lines that do not include the specified character using the grep command, then use the sed command to output the results to a new file, and finally use the mv command to overwrite the original file with the new one.
To delete lines in the file file.txt that contain the specified character “abc”, you can follow these steps:
- Filter out lines that do not contain specific characters using the grep command.
- Exclude lines containing “abc” from file.txt and save the result in newfile.txt.
- Use the “sed” command to redirect the output to a new file.
- Delete any lines containing the string “abc” from the file.txt and save the result in newfile.txt.
- Use the “mv” command to replace the original file with the new file.
- rename newfile.txt to file.txt
Any of the three methods above can achieve the function of deleting lines containing a specified character.