How to use sed to replace an environment variable

Solution 1:

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)