How to Use sed to Print All Lines After Line with Match


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

You can use the following methods to do so:

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

sed -ne '/Orlando/,$ p' cities.txt

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

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

sed -e '1,/Orlando/ d' cities.txt

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

Note: This method uses the d flag in sed to delete every line ranging from the first line through the line that contains Orlando, which is the same as print every line after the line that matches Orlando.

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: Print All Lines After Line with Match (Including Match)

Suppose that we would like to print every line 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 -ne '/Orlando/,$ p' cities.txt

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

sed print all lines after line with match

Notice that this prints every line after (and including) the line that matches the pattern Orlando in the file named cities.txt.

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

Suppose that we would like to print every line 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 -e '1,/Orlando/ d' cities.txt

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

sed print all lines after line with match, excluding match

Notice that this prints every line 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