Linux / Unix: Sed Delete Matching Words In A File

You can use the sed command in Linux and Unix to delete matching words from a file. The sed command is a powerful stream editor that can perform various text transformations on a file.

Here’s an example of how you can use sed to delete matching words from a file:

$ sed '/word_to_delete/d' input_file > output_file

In this example, sed reads the input_file and applies the /word_to_delete/d command, which deletes all lines that contain the word “word_to_delete”. The result is redirected to a new file output_file.

You can also use sed to delete matching words in-place, meaning that the changes are made directly to the original file, without creating a new file. To do this, use the -i option:

$ sed -i '/word_to_delete/d' input_file

In this example, the -i option tells sed to make the changes directly to the input_file and to make a backup of the original file before making changes. By default, the backup file will have the same name as the original file with the suffix .bak.

You can also specify a different backup suffix using the -i option. For example:

$ sed -i.bak2 '/word_to_delete/d' input_file

In this example, the backup file will have the name input_file.bak2.

Leave a Comment