0

I have a specific text: ==4 to be replaced by ==5. So, I initialized two variables with $i and $j with 4 and 5 respectively and used this sed command to do the work:

sed -i 's/==${i}/==${j}/g' "filename.txt"

When I echo ==${i}, I get ==4 and similar for the j but the above sed command doesn't work or doesn't replace ==4 with ==5. What am I missing here? Is == the problem here?

I am using Linux.

terdon
  • 242,166
ShAd
  • 16
  • 1
  • 1
    Don't use single quotes when work with variables, use double quotes: sed -i "s/==${i}/==${j}/g" "filename.txt" – Edgar Magallon Dec 05 '22 at 05:08
  • Note that embedding shell variables inside sed scripts can cause problems in sed (e.g. if one of the variables that you're using in a s/// operation contains a literal / character)...unless you're certain your vars wont cause syntax errors in sed, it's safer to use awk or perl (which both have several methods for passing shell vars into awk or perl vars, while sed doesn't really have a concept of variables). Also, this question has been asked many times before, too many to pick just one duplicate - see https://unix.stackexchange.com/search?q=sed+variable+quote – cas Dec 05 '22 at 05:17

0 Answers0