How to use sed's substitute with a regex pattern as variable?

Let us say that we have the following as stdin (as an example)

Life is temporary

I want sed to replace this with

Life is permanent

with 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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like