How to use variables in a command in sed?

UnixSed

Unix Problem Overview


I have abc.sh:

exec $ROOT/Subsystem/xyz.sh

On a Unix box, if I print echo $HOME then I get /HOME/COM/FILE.

I want to replace $ROOT with $HOME using sed.

Expected Output:

exec /HOME/COM/FILE/Subsystem/xyz.sh

I tried, but I'm not getting the expected output:

sed  's/$ROOT/"${HOME}"/g' abc.sh > abc.sh.1

Addition:

If I have abc.sh

exec $ROOT/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh

then with

sed "s|\$INSTALLROOT/|${INSTALLROOT}|" abc.sh

it is only replacing first $ROOT, i.e., output is coming as

exec /HOME/COM/FILE/Subsystem/xyz.sh $ROOT/ystem/xyz1.sh

Unix Solutions


Solution 1 - Unix

Say:

sed "s|\$ROOT|${HOME}|" abc.sh

Note:

  • Use double quotes so that the shell would expand variables.
  • Use a separator different than / since the replacement contains /
  • Escape the $ in the pattern since you don't want to expand it.

EDIT: In order to replace all occurrences of $ROOT, say

sed "s|\$ROOT|${HOME}|g" abc.sh

Solution 2 - Unix

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1

Solution 3 - Unix

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Solution 4 - Unix

The safe for a special chars workaround from https://www.baeldung.com/linux/sed-substitution-variables with improvement for \ char:

#!/bin/bash
to="/foo\\bar#baz"
echo "str %FROM% str" | sed "s#%FROM%#$(echo ${to//\\/\\\\} | sed 's/#/\\#/g')#g"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVJSView Question on Stackoverflow
Solution 1 - UnixdevnullView Answer on Stackoverflow
Solution 2 - UnixpotongView Answer on Stackoverflow
Solution 3 - UnixpratibhaView Answer on Stackoverflow
Solution 4 - UnixMihail H.View Answer on Stackoverflow