Variable inside sed

Problem: Need to read contents from a file and use that value inside sed as avariable. sample code below. THe below code replaces contents inside file123 for matched string with "$x" value only. but we want the value of x which is read from TextFile.txt to go in there.

cat TextFile.txt|while read x
do
cat file123 | sed -e 's/string1/$x/g'
done

please let me know.

No need for the cat s and use double quotes or additions single quotes to persuade the shell to substitute your variable:

while read x
do
     sed -e 's/string1/'$x'/g' file123
done < TextFile.txt

Or with double quotes:

while read x
do
     sed -e "s/string1/$x/g" file123
done < TextFile.txt
2 Likes

Use double quotes instead of single quotes. This should work as long as $x does not contain forward slashes. This script will replace every string1 on every line in file123 with the first line of TextFile.txt, is that what you want to achieve?

By the way, you can avoid the double UUOC , like so:

while read x
do
  sed "s/string1/$x/g" file123
done < TextFile.txt
1 Like

thanks and it works