Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed replace value with variable [duplicate]

Tags:

bash

shell

sed

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

like image 386
Tobi Avatar asked Oct 11 '25 09:10

Tobi


2 Answers

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
like image 154
user unknown Avatar answered Oct 16 '25 08:10

user unknown


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'
like image 30
Walter A Avatar answered Oct 16 '25 07:10

Walter A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!