Home > OS >  Sed find and replace expression works with literal but not with variable interpolation
Sed find and replace expression works with literal but not with variable interpolation

Time:01-29

For the following MVCE:

echo "test_num: 0" > test.txt
test_num=$(grep 'test_num:' test.txt  | cut -d ':' -f 2)
new_test_num=$((test_num   1))

echo $test_num
echo $new_test_num

sed -i "s/test_num: $test_num/test_num: $new_test_num/g" test.txt
cat test.txt

echo "sed -i "s/test_num: $test_num/test_num: $new_test_num/g" test.txt"

sed -i "s/test_num: 0/test_num: 1/g" test.txt
cat test.txt

Which outputs

0 # parsed original number correctly
1 # increment the number
test_num: 0 # sed with interpolated variable, does not work
sed -i s/test_num: 0/test_num: 1/g test.txt # interpolated parameter looks right
test_num: 1 # ???

Why does sed -i "s/test_num: $test_num/test_num: $new_test_num/g" test.txt not produce the expected result when sed -i "s/test_num: 0/test_num: 1/g" test.txt works just fine in the above example?

CodePudding user response:

As mentioned in the comment, there is a white space in ${test_num}. Therefore in your sed there should not be an empty space between the colon and your variable.

Also I guess you should surround your variable with curly bracket {} to increase readability.

sed "s/test_num:${test_num}/test_num: ${new_test_num}/g" test.txt 
test_num: 1

If you just want the number in ${test_num}, you can try something like:

grep 'test_num:' test.txt | awk -F ': ' '{print $2}'

awk allows to specify delimiter with more than 1 character.

CodePudding user response:

Instead of grep|cut you can also use sed.

#! /bin/bash

exec <<EOF
test_num: 0
EOF

grep 'test_num:' | cut -d ':' -f 2

exec <<EOF
test_num: 0
EOF

sed -n 's/^test_num: //p'
  •  Tags:  
  • Related