How to Use sed to Delete All Lines Containing Specific String


Often you may want to use sed to delete all lines from a file that contain a specific string.

You can use the following basic syntax to do so:

sed -i '/West/d' teams.txt

This particular example deletes all lines from the file named teams.txt that contain the string “West” anywhere in the line.

Note that we use the -i flag in sed to delete the lines in-place.

If you simply want to delete the lines and show the resulting output then you can leave out this flag.

The following example shows how to use this syntax in practice.

Example: Use sed to Delete All Lines Containing Specific String

Suppose we have a text file named teams.txt that contains the following lines:

Suppose that we would like to delete all lines from the teams.txt file that contain the string “West” anywhere in the line.

We can use the following syntax to do so:

sed -i '/West/d' teams.txt

The following screenshot shows how to use this syntax in practice:

sed delete lines containing string

Notice that when we use the cat command again to view the contents of the file that all lines with “West” somewhere in the line have been deleted.

Feel free to replace West with a different pattern to delete lines containing a different pattern from the file.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply