0

I'm familiar with sed's ability to replace in-place in a file, as answered here: sed edit file in place.

I.e. sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' filename

I'm having trouble expanding this concept to replacing a string-literal that takes the form of a shell-variable -- how does one do this?

To illustrate with an example:
Given file file.txt:

# file.txt
set(FOO ${FOO})

...and shell environment variable ${FOO}:

$ FOO=bar
$ echo ${FOO}
bar

...how can I use sed to replace string-literal "${FOO}" in file.txt with the value of shell-variable ${FOO} i.e. "bar"? I.e. I'd like the resulting content of file.txt to be:

# file.txt
set(FOO bar)

I have a mental block thinking past the obviously-incorrect sed -i 's/${FOO}/${FOO}/g' file.txt

I gravitate towards sed because of past experience, and might prefer a sed-centric answer for the same reason. But any solution is probably okay, but with a preference for POSIX-compliance, if shell-native. To be even more specific, this is going to be run in a docker container with a debian-10.3 base...so I suppose solutions that work with any tools included in that distro should be okay as well.

StoneThrow
  • 5,314
  • 4
  • 44
  • 86
  • 1
    For sed use double quotes: `sed -i "s/\${FOO}/${FOO}/g" file.txt` – anubhava Apr 29 '21 at 19:22
  • @anubhava - thank you; please post an answer if you're able to share details on your solution: why it works, what's different vs. my obviously-incorrect attempt, etc. – StoneThrow Apr 29 '21 at 19:25

0 Answers0