79

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
3

4 Answers 4

151

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
1
  • 1
    This completely did the trick. In case it helps anyone out, I did something like this: sed "s|@@ALF_INSTALL_DIR|${ALF_INSTALL_DIR}|g" files/tomcat/alfresco-global.properties.template > files/tomcat/alfresco-global.properties The variable contains "/" because it has a path to it (fwiw).
    – Harlin
    May 16, 2020 at 15:21
27

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
1
  • thanks, I had to add | sed 's/[{}]//g' to remove the brackets, but otherwise it worked Nov 24, 2021 at 17:12
0
This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile
2
  • This could be problematic if input or output contains a slash
    – kvantour
    May 7, 2020 at 12:02
  • I would want to have date variable and it looks like currentDate=$date sed -i '12s|(.*)|<h1 style="text-align:center;">My Report</h1><h3>Executed by: My Build tool </h3><h3>Executed on: $currentDate</script></h2>\1|' <<path to HTML file>> As we see, currentDate is being used in sed -i command. Is it possible to make it work ? Jun 9, 2020 at 17:24
-1

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"

Not the answer you're looking for? Browse other questions tagged or ask your own question.