How to Use awk to Delete All Lines Matching a Pattern


Often you may want to use awk to delete all lines in a file matching a specific pattern.

You can use the following basic syntax to do so:

awk '!/Mavs/' players.txt

This particular example will delete all lines matching the pattern Mavs in the file named players.txt.

Note that we use the ! character as a “NOT” operator to specify that we simply want to keep all lines that do not contain the pattern Mavs.

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

Example: How to Use awk to Delete All Lines Matching a Pattern

Suppose that we have the following file named players.txt that contains information about various basketball players:

Suppose that we would like to delete all lines that contain the pattern Mavs anywhere in the line.

We can use the following syntax to do so:

awk '!/Mavs/' players.txt

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

awk delete lines matching pattern

Notice that all lines that contained the pattern Mavs have been deleted.

If you’d like, you can use the > command to save these results to a new file:

awk '!/Mavs/' players.txt > players_new.txt

This particular example would delete all lines that contain the pattern Mavs from the file named players.txt and save the results to a new file name players_new.txt.

Related Tutorials

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

How to Use awk to Print All Columns After Specific Number
How to Use awk to Print Rows Where Column Equals Value
How to Use awk to Print Last Line of a File
How to Use awk to Print a Range of Columns

Leave a Reply