replace string in a file with another where both are saved in variables

replace string in a file with another where both are saved in variables

I want to replace a string found in a file with another string, but both have a special character (in this example it is a . char) e.g 1.0 and 2.0

so this the is command currently used:

sed -i 's/1\.0/2\.0/g' /home/user1/file1.txt

what if 1.0 and 2.0 were saved in variables $i and $j? where i has the value 1.0 and j has the value 2.0, how I can still the replace i with j?

EDIT:

As muru suggested, I used the double quotes as suggested and it works okay only if $i and $j were saved as 1.0 and 2.0 I doesn't work correctly if $i and $j where saved as 1.0 and 2.0 could anyone please advise how to fix this?

EDIT2:

As muru suggested, I followed the answer found here but still the result is not correct.

This is my shell file:

declare -a arr1=("1.0" "2.0" "3.0" "4.0")
ii=1.0
for i in "${arr1[@]}"
do
    str2=$i
    echo -e "\e[41m## str2 = $str2 ##\e[0m" 
    echo -e "\e[41m## $ii $str2 ##\e[0m"
    printf '%s\n' "$ii" "$str2" |
    file=/home/user1/text1.txt
    tmpfile="${TMPDIR:-/tmp}/$( basename "$file" ).$$"
    while read line
    do
      echo ${line/$ii/$str2}
    done < "$file" > "$tmpfile" && mv "$tmpfile" "$file"

    ii=$str2

done

this is my text1.txt file:

0 0 -1 0
1 0 0 0
0 -1 0 0
1.5 0.0 1.0 1

and this is the result:

0 0 -4.0
4.0 0 0
0 -4.0 0
1.5 0.0 2.5 1

and the correct result should be:

0 0 -1 0
1 0 0 0
0 -1 0 0
1.5 0.0 4.0 1

答案1

Use perl instead. It has an interesting quotemeta feature in regular expressions where it will handle special characters like ., *, etc as plain characters

$ i=1.0  j=4.0
$ perl -pe "s/\Q$i/$j/g" text1.txt 
0 0 -1 0
1 0 0 0
0 -1 0 0
1.5 0.0 4.0 1

It's documented here: http://perldoc.perl.org/functions/quotemeta.html

答案2

Sorry, I misunderstood a bit... this:

only covers the replacement string.

For exact matching in the search string, I don't think sed is your tool, you want the answer that @muru posted as well:

Good luck

相关内容