How to Use sed to Delete n Lines Following a Pattern


Often you may want to use sed to delete n lines following a line that contains a specific pattern.

You can use the following methods to do so:

Method 1: Delete n Lines After Pattern (Including Line with Pattern)

sed -e '/Houston/,+4d' cities.txt

This particular example deletes 4 lines after the line that contains “Houston”, including the line with the matching pattern.

This example works by using Houston/,+4 to define a range of lines starting at the line with Houston and continuing for 4 total lines, then by using the d command to delete each line in this range.

Method 2: Delete n Lines After Pattern (Not Including Line with Pattern)

sed -e '/Houston/{n;N;N;N;d}' cities.txt

This particular example deletes 4 lines after the line that contains “Houston”, not including the line with the matching pattern.

This example works by matching the line that contains Houston, then printing the next line (n;) then using d to delete the next 3 (N;) lines.

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

Example 1: Delete n Lines After Pattern (Including Line with Pattern)

We can use the following syntax to delete 4 lines after the line that matches the pattern “Houston”, including the matching line:

sed -e '/Houston/,+4d' cities.txt

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

sed replace n lines following pattern

Notice that this syntax deletes 4 lines after the line that matches the pattern “Houston”, including the matching line:

  • Dallas
  • Boston
  • Houston
  • Sacramento
  • Orlando
  • Cincinnati
  • Memphis
  • Milwaukee
  • Chicago

Example 2: Delete n Lines After Pattern (Not Including Line with Pattern)

We can use the following syntax to delete 4 lines after the line that matches the pattern “Houston”, including the matching line:

sed -e '/Houston/{n;N;N;N;d}' cities.txt

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

Notice that this syntax deletes 4 lines after the line that matches the pattern “Houston”, including the matching line:

  • Dallas
  • Boston
  • Houston
  • Sacramento
  • Orlando
  • Cincinnati
  • Memphis
  • Milwaukee
  • Chicago

Feel free to use whichever method you prefer.

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