How to Use sed to Extract All Lines Containing a Pattern


Often you may want to use sed to extract all lines from a file that contain a specific pattern.

You can use the following methods to do so:

Method 1: Extract All Lines Containing One Specific Pattern

sed -n '/West/p' teams.txt

This particular example extracts all lines from the file named teams.txt that contain the string “West” anywhere in the line.

Method 2: Extract All Lines Containing One of Several Specific Patterns

sed -n '/Celtics/p;/West/p' teams.txt

This particular example extracts all lines from the file named teams.txt that contain the string “Celtics” or the string “West” anywhere in the line.

The following example shows how to use each method in practice with a text file named teams.txt that contains the following lines:

Example 1: Use sed to Extract All Lines Containing One Specific Pattern

Suppose that we would like to extract all lines from the teams.txt file that contain the string “West” anywhere in the line.

We can use the following syntax to do so:

sed -n '/West/p' teams.txt 

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

sed extract lines matching pattern

Notice that this returns all lines from the file that contain “West” anywhere in the line.

Example 2: Use sed to Extract All Lines Containing One of Several Specific Patterns

Suppose that we would like to extract all lines from the teams.txt file that contain the string “Celtics” or the string “West” anywhere in the line.

We can use the following syntax to do so:

sed -n '/Celtics/p;/West/p' teams.txt

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

sed extract lines containing one of several patterns

Notice that this returns all lines from the file that contain “Celtics” or “West” anywhere in the line.

Related Tutorials

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

How to Use sed to Replace newline with space
How to Use sed to Replace newline with comma
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply