How to Use sed to Replace String Between Two Patterns


Often you may want to use sed to replace a string between two patterns.

You can use the following basic syntax to do so:

sed 's/Team.*Position/Team INFO Position/g' team_info.txt

This particular example replaces the existing string between the patterns Team and Position with the new string INFO for each line in the file named team_info.txt.

Note that we used the s command to “substitute” one pattern for another and we used the g command to make this substitution “globally”, i.e. for all occurrences.

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

Example: Use sed to Replace String Between Two Patterns

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

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

Suppose that we would like to replace the string between the patterns Team and Position in each line of the file with the new string INFO.

We can use the following syntax to do so:

sed 's/Team.*Position/Team INFO Position/g' team_info.txt

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

sed replace pattern between two strings

Notice that each string between the patterns Team and Position has been replaced with the new string INFO on each line of the file.

Note that you could use the -i flag to save these changes to the file in-place if you would like:

sed -i 's/Team.*Position/Team INFO Position/g' team_info.txt

This would save the changes made to the team_info.txt file in-place.

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 All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply