3

I have a variable in a config, which I would like to replace with a value.

ROOT="rROOT"

I would like to replace that with

ROOT="$root"

So with the value of $root (Important are the quotation marks).

So far I have tried it that way

sed -i s/'ROOT=rROOT'/'ROOT="$root"'/g $directory/settings.conf

The result is that

ROOT="$root"

But this is stored in the variable $root (It is always a path)

root: /

How can I replace rROOT with the value of $root?

Sed Version: (GNU sed) 4.2.2

Tobi
  • 31
  • 2
  • 5

2 Answers2

5

Ok, don't like to ruin my scripts for testing:

cat tageslog.sh | sed "s/alt=185094/alt=\${root}/g"

Use double quotes, but mask the dollar sign, so it doesn't get lost and root interpreted while calling sed.

Use ${root} instead of "$root".

sed "s/ROOT=.rRoot./ROOT=\${root}/g" $directory/settings.conf

if this works, use the -i switch:

sed -i "s/ROOT=.rRoot./ROOT=\${root}/g" $directory/settings.conf
user unknown
  • 35,537
  • 11
  • 75
  • 121
0

You have different problems:

  • Testing with echo
    I think you tested your command with
    echo ROOT="rROOT" | sed s/'ROOT=rROOT'/'ROOT="$root"'/g
    The double quotes won't appear in the output of the echo, so you will end up with a command working for ROOT=rROOT.
    When the inputfile has qouble quotes, you do not have to insert them.
    Testing with the double quotes is possible with
    echo 'ROOT="rROOT"' | sed s/'ROOT=rROOT'/'ROOT="$root"'/g
  • Place the double quotes outside the single quotes; You can test this with echo:
    echo 'Showing "$PWD" in double quotes is "'$PWD'"'
    echo 'With additional spaces the last part is " '$PWD' " '
  • Root vaiable has slashes that will confuse sed.
    The root variable is replaced before sed tries to understand the command.
    You can use another character, like #, in the sed command: sed 's#before#after#'

When your input has double quotes:

echo 'ROOT="rROOT"' | sed 's#ROOT="rROOT"#ROOT="'$root'"#g'
# or by remembering strings
echo 'ROOT="rROOT"' | sed -r 's#(ROOT=")rROOT(")#\1'$root'\2#g'

Input without double quotes

echo 'ROOT=rROOT' | sed 's#ROOT=rROOT#ROOT="'$root'"#g'
# or by remembering strings
echo 'ROOT=rROOT' | sed -r 's#(ROOT=)rROOT#\1"'$root'"#g'
Walter A
  • 19,067
  • 2
  • 23
  • 43