Inacio Inacio - 1 year ago 61
Bash Question

Space interferes in sed replacement using shell variables

I am using sed in a shell script to replace a word in a file with a sentence that is stored in a shell variable. The sentence contains spaces and different characters.


sentence="new number is > than 2.5 and < than 3.8"
sed "s|word|$sentence|g" -i Example_file.txt

Line in the file:

tile = "word - Final plot"

expected result:

title = "new number is > than 2.5 and < than 3.8 - Final plot"

obtained result:

title = "new - Final plot"

As you can see above, the problem is that
always replaces "word" only with the first word of the sentence, it stops at the space. I tried different variations of the command:

sed 's|word|'"$sentence"'|g' -i Example_file.txt
sed "s|word|${sentence}|g" -i Example_file.txt

None of that seems to work. To check if the spaces were indeed the problem I replaced them with
, and when I do that,
replaces using the whole sentence.

Anyone knows how can I force sed to take in the spaces and use the whole sentence?

Answer Source

Try this, based on fixing what I THINK your comment under your question is telling us you are currently doing:


sed 's/\<word\>/'"$1"'/' abc.txt


sentence="new number is > than 2.5 and < than 3.8"
./file1 "$sentence"

Google "quote your shell variables". The above assumes you have GNU sed for word boundaries \<...\>. If you don't then get rid of them to see if it works then we can talk about how you address the need for them in other seds.