Linux / Unix: Sed Delete Matching Words In A File

Linux / Unix: Sed Delete Matching Words In A File

To delete matching words in a file using the sed command, you can use the d command.

For example, to delete all lines that contain the word hello, you can use the following command:

refer‮ ‬to:lautturi.com
sed '/hello/d' input.txt > output.txt

This will read the file input.txt, delete all lines that contain the word hello, and save the resulting output to output.txt.

You can also use the -i option to edit the file in place, rather than creating a new output file. For example:

sed -i '/hello/d' input.txt

This will delete all lines that contain the word hello from the file input.txt.

You can use the -n option to suppress the default output, and only print the lines that match a specific pattern. For example:

sed -n '/hello/p' input.txt

This will print only the lines that contain the word hello from the file input.txt.

You can also use regular expressions to match patterns in the sed command. For example, to delete all lines that contain the word hello followed by a space and a number, you can use the following command:

sed '/hello [0-9]/d' input.txt > output.txt

This will delete all lines that contain the pattern hello followed by a space and a number from the file input.txt and save the resulting output to output.txt.

For more information about using the sed command, you can refer to the sed manual page or use the --help option. For example:

man sed
sed --help
Created Time:2017-10-29 22:08:59  Author:lautturi