How to use sed to replace an environment variable

I have the following strings in a file

$ENVVAR
someText ($ENVVAR)

I want to use sed so that only the second occurence of the variable is replaced with the value of the environment variable

so

$ENVVAR
someText (value of env variable)
0

1 Answer

This is a case for some ugly fancy quoting. Single quotes stop shell parameter expansions, and double quotes to allow them.

You can think of quotes as on-off switches in a sed expression, closing one type of quoting and opening another like this: 'strong'"weak"'strong'

Using $USER as an example:

$ cat file
$USER
some text ($USER)
$ sed 's/($USER)/('"$USER"')/' file
$USER
some text (zanna)
0

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