How to Use sed to Delete All Lines After Match


Often you may want to use sed to delete all lines in a file after a line that matches a specific pattern.

You can use the following methods to do so:

Method 1: Delete All Lines After Line with Match (Including Match)

sed '/Orlando/,$d' cities.txt

This particular example will delete all lines after (and including) the line that matches the pattern Orlando in the file named cities.txt.

This method uses the d command to tell sed to delete all lines from the output starting at the line that matches Orlando and continuing until the last ($) line in the file.

Method 2: Delete All Lines After Line with Match (Not Including Match)

sed '/Orlando/q' cities.txt

This particular example will delete all lines after (not including) the line that matches the pattern Orlando in the file named cities.txt.

This method uses the q command to tell sed to print all lines and quit when the pattern Orlando is matched.

The following examples show how to use each method in practice with a file named cities.txt that contains the names of various U.S. cities:

Example 1: Delete All Lines After Line with Match (Including Match)

Suppose that we would like to delete all lines after (and including) the line that matches the pattern Orlando in the file named cities.txt.

We can use the following syntax to do so:

sed '/Orlando/,$d' cities.txt

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

sed delete all lines after match

Notice that this deletes all lines after (and including) the line that matches the pattern Orlando in the file named cities.txt.

Example 2: Delete All Lines After Line with Match (Not Including Match)

Suppose that we would like to delete all lines after (not including) the line that matches the pattern Orlando in the file named cities.txt.

We can use the following syntax to do so:

sed '/Orlando/q' cities.txt

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

Notice that this deletes all lines after (not including) the line that matches the pattern Orlando in the file named cities.txt.

Related Tutorials

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

How to Use sed to Print Out Line Numbers
How to Use sed to Print Specific Lines in File
How to Use sed to Print Every nth Line of File
How to Use sed to Extract All Lines Containing a Pattern

Leave a Reply