72

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
Benjamin W.
  • 38,596
  • 16
  • 96
  • 104
VJS
  • 2,759
  • 6
  • 33
  • 61
  • possible duplicate of [replace a string in shell script](http://stackoverflow.com/questions/3306007/replace-a-string-in-shell-script) – tripleee Oct 03 '13 at 06:54
  • 4
    @tripleee While I'm certain that this would be a duplicate of numerous other questions, the one that you've pointed to isn't the best one since it doesn't contain slashes in the variable. All answers therein use `/` as the separator. Obvious stuff, I know but leaves room for a better (duplicate) question. – devnull Oct 03 '13 at 11:07

4 Answers4

139

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
oguz ismail
  • 39,105
  • 12
  • 41
  • 62
devnull
  • 111,086
  • 29
  • 224
  • 214
  • 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 '20 at 15:21
26

This might work for you:

sed 's|$ROOT|'"${HOME}"'|g' abc.sh > abc.sh.1
potong
  • 51,370
  • 6
  • 49
  • 80
1
This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile
pratibha
  • 11
  • 1
  • This could be problematic if input or output contains a slash – kvantour May 07 '20 at 12:02
  • I would want to have date variable and it looks like currentDate=$date sed -i '12s|\(.*\)|

    My Report

    Executed by: My Build tool

    Executed on: $currentDate\1|' <> As we see, currentDate is being used in `sed -i` command. Is it possible to make it work ?

    – user9920500 Jun 09 '20 at 17:24
0

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"
Mihail H.
  • 1,254
  • 12
  • 14