How to Use Sed to Replace an Environment Variable

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

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

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.