How to Use sed to Replace Exact Match (With Example)


Often you may want to use sed to replace only an exact matching pattern in a string.

You can use the following basic syntax to do so:

sed 's/\<West\>/NEW/' regions.txt

This particular example replaces the exact matching pattern West with the pattern NEW for each line in the file named regions.txt.

Note that we used the s command to “substitute” one pattern for another and we used \< and \> to specify that we’d like to exactly match West with no other characters on either side of the pattern.

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

Example: How to Use sed to Replace Exact Match

Suppose that we have a file named regions.txt that contains the names of various sales regions for some company.

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

Suppose that we would like to replace only the lines that exactly match the text West with the text NEW.

Suppose we attempt to use the following syntax to do so:

sed 's/West/NEW/' regions.txt

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

Notice that any string that contains the text West has been replaced with the text NEW.

However, suppose that we only want to replace strings that contain the exact text West with no other text around it.

We can use the following syntax to replace this exact match:

sed 's/\<West\>/NEW/' regions.txt

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

sed replace exact match

Notice that only the first line that contained the exact text West has been replaced with NEW.

By using the \< and \> symbols in the sed s command, we were able to only replace exact matching patterns.

Related Tutorials

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

How to Use sed to Replace nth Occurrence of Pattern
How to Use sed to Replace Last Line Matching Pattern
How to Use sed to Replace All Occurrences of Pattern
How to Use sed to Replace All Text After Match

Leave a Reply