Monday, September 5, 2022

[SOLVED] Replacing string in a file by bash variable

Issue

How to replace a string in a file by bash variable, please

I tried

  i="1"
  sed -i 's/%q/0$i/g' file
  sed -i 's/%q/0"$i"/g' file

There is 0$i or 0"$i" in the file instead of 01. Thank you


Solution

Change your script as follow:

i="1"
sed -i "s/%q/0$i/g" file
sed -i "s/%q/0\"$i\"/g" file

and remember: the shell variables substitution does not happen inside single quotes. ;)



Answered By - Antonio Petricca
Answer Checked By - Pedro (WPSolving Volunteer)