Let us say that we have the following as stdin (as an example)
Life is temporaryI want sed to replace this with
Life is permanentwith a command somewhere along the lines of
sed 's/Life<%XY=.*>temporary/Life%XYpermanent'
Of course, I know that the above is not a valid command, it is to serve as an example. I want to store whatever that .* matches into a variable, and I want to recall that variable in the replace string.
1 Answer
sed 's/Life\(.*\)temporary/Life\1permanent/'Here \1 refers to the first pair of parentheses in the pattern. It's the only pair in this case, but in general you can have more pairs and then you can use \2, \3 etc., up to \9.
The parentheses are escaped. Without \ they would be taken literally and \1 wouldn't work. If you use sed -E then it will be reversed: ( will be special and \( will denote a literal ( (note in general it's not the only difference -E makes):
sed -E 's/Life(.*)temporary/Life\1permanent/'This change makes our sed code somewhat more readable for humans.