How to Use sed to Delete All Lines that Do Not Match Pattern


Often you may want to use sed to delete all lines from a file that do not match a specific pattern.

You can use the following basic syntax to do so:

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

This particular example deletes all lines that do not contain West in the file named teams.txt.

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

If you’d like to store the results to a new file then you can use the following syntax:

sed '/West/!d' teams.txt > teams_new.txt

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

Note: The d operator is used to delete lines. By using !d we specify that we’d like to delete all lines that do not match a particular pattern.

Example: Use sed to Delete All Lines that Do Not Match Pattern

Suppose we have a text file named teams.txt that contains information about various basketball teams:

Suppose that we would like to delete all lines from the file that do not contain the string West somewhere 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 if not match

Notice that when we use the cat command again to view the contents of the file that all lines that did not contain the string West have been deleted.

Note that we could also use the following syntax to delete all lines that do not contain West and save the results to a new file:

sed '/West/!d' teams.txt > teams_new.txt

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

sed delete line if not match and save results to new file

Notice that when we use the cat command to view the contents of the file named teams_new.txt that it only contains the lines from the original file that contained West somewhere in the line.

Related Tutorials

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

How to Use sed to Delete Specific Line Numbers from File
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