How to Use sed to Print All Lines Between Two Patterns


Often you may want to use sed to print every line between two specific patterns in a file.

You can use the following methods to do so:

Method 1: Print All Lines Between Two Patterns (Including Patterns)

sed -n '/Boston/,/Memphis/p' cities.txt

This particular example will print every line between the two lines that contain the patterns Boston and Memphis in the file named cities.txt, including the lines that contain the patterns.

Method 2: Print All Lines Between Two Patterns (Excluding Patterns)

sed -n '/Boston/,/Memphis/{//!p}' cities.txt

This particular example will print every line between the two lines that contain the patterns Boston and Memphis in the file named cities.txt, excluding the lines that contain the patterns.

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 Between Two Patterns (Including Patterns)

Suppose that we would like to print every line between the two lines that contain the patterns Boston and Memphis in the file named cities.txt, including the lines that contain these patterns.

We can use the following syntax to do so:

sed -n '/Boston/,/Memphis/p' cities.txt

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

sed print lines between patterns, including lines with patterns

Notice that this prints every line in the file between the two lines that contain the patterns Boston and Memphis, including those lines that contain the patterns.

Example 2: Print All Lines Between Two Patterns (Excluding Patterns)

Suppose that we would like to print every line between the two lines that contain the patterns Boston and Memphis in the file named cities.txt, excluding the lines that contain these patterns.

We can use the following syntax to do so:

sed -n '/Boston/,/Memphis/{//!p}' cities.txt

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

sed print lines between patterns, exclusive

Notice that this prints every line in the file between the two lines that contain the patterns Boston and Memphis, not including those lines that contain the patterns.

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