Tuesday, October 25, 2022

[SOLVED] Sed string replace using environment variable

Issue

I have a situation where variables are set in the environment and I have to replace those variable in the file with its value.

Example, I have a lot variable set few of them are FRUIT=APPLE, TIME=DAILY. The content of the text file is

The $$FRUIT$$ is good for health. Everyone should eat $$FRUIT$$ $$TIMES$$.

Now I want a sed command to search any string in $$$$ and use it as env variable to get the value and replace it in the file.

The APPLE is good for health. Everyone should eat APPLE DAILY.

I tried

sed -i -E "s|$$([A-Z]+)$$|${\1}|g" test.txt

and multiple other combination, but its not working.

it gives me error -bash: s|$$([A-Z]+)$$|${\1}|g: bad substitution


Solution

This steals from the answer to How can I interpret variables on the fly in the shell script? -- this question isn't quite a duplicate of that one.

Provided that the variables are part of the environment:

export FRUIT="APPLE"
export TIMES="DAILY"

You can use the envsubst GNU tool to perform the variable replacement:

echo 'The $$FRUIT$$ is good for health. Everyone should eat $$FRUIT$$ $$TIMES$$.' | sed -E 's/\$\$([A-Z]+)\$\$/${\1}/g' | envsubst
The APPLE is good for health. Everyone should eat APPLE DAILY.

Note that you need to put a backslash before the $ character since this character has a meaning for sed.



Answered By - oliv
Answer Checked By - Willingham (WPSolving Volunteer)