How to replace a character within a matched pattern using ampersand (&)

user1418321 picture user1418321 · Oct 2, 2012 · Viewed 42.6k times · Source

When we match a pattern using sed, the matched pattern is stored in the "ampersand" (&) variable. IS there a way to replace a character in this matched pattern using the ampersand itself ?

For example, if & contains the string "apple1", how can I use & to make the string to "apple2" (i.e replace 1 by 2) ?

Answer

Elias Dorneles picture Elias Dorneles · Oct 2, 2012

If I guessed right, what you want to do is to apply a subsitution in a pattern matched. You can't do that using &. You want to do this instead:

echo apple1 apple3 apple1 apple2 botemo1 | sed '/apple./ { s/apple1/apple2/g; }'

This means that you want to execute the command substitution only on the lines that matches the pattern /apple./.