How would I use sed to delete all lines in a text file that contain a specific string?

 

You can use the sed command to delete all lines in a text file that contain a specific string by using the following syntax:

bash
sed '/pattern/d' inputfile > outputfile

Here's a breakdown of the command:

  • sed: This is the Stream Editor, a Unix command-line utility for manipulating text.
  • /pattern/: This is the pattern or string you want to search for in each line of the input file.
  • d: This is the sed command to delete lines that match the pattern.
  • inputfile: This is the name of the input file from which you want to remove lines.
  • outputfile: This is the name of the file where the modified text will be saved. If you want to modify the original file in-place, you can use the -i option with sed, but be cautious as it will overwrite the original file.

Here's an example of how to use sed to delete all lines containing a specific string from a file:

Let's say you have a file named example.txt with the following content:

vbnet
This is line 1. This line contains the string to be deleted. This is line 3. Another line with the string to be deleted. This is line 5.

To delete all lines containing the string "to be deleted," you can run the following sed command:

bash
sed '/to be deleted/d' example.txt > newfile.txt

After running this command, the lines containing the specified string will be removed, and the remaining content will be saved in a new file named newfile.txt. The example.txt file will remain unchanged. The contents of newfile.txt will look like this:

arduino
This is line 1. This is line 3. This is line 5.

If you want to modify the original file in-place, you can use the -i option like this:

bash
sed -i '/to be deleted/d' example.txt

This will directly modify example.txt, removing the lines containing the specified string.

Comments