How to Use sed to Replace Entire Line that Contains Pattern


Often you may want to use sed to replace an entire line that contains a particular pattern in a file.

You can use the following syntax to do so:

sed -i '/West/c\Western Team' teams.txt

This particular example replaces each entire line that contains the pattern “West” with the new text “Western Team” in the file named teams.txt.

Note that we use the -i flag to specify that the changes should be made to the file in-place.

We also use the c command to specify that the entire line should be changed.

The following example shows how to use this syntax in practice.

Example: How to Use sed to Replace Entire Line that Contains Pattern

Suppose that we have a file named named teams.txt that contains information about various basketball teams.

We can use the cat command to view the contents of this file:

Suppose that we would like to replace the entire contents of each line that contains the pattern “West” with the new text “Western Team” instead.

We can use the following syntax to do so:

sed -i '/West/c\Western Team' teams.txt

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

sed replace entire line

Each line that contained the pattern “West” anywhere in the line has been replaced with the text “Western Team” instead.

Feel free to use similar syntax to replace entire lines in your own file based on your own specific patterns.

Related Tutorials

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

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

Leave a Reply