I cannot not use a shell variable in sed in the $NUMBER form. I have this line in my shell script:

cat shared.txt sed 's/whatever1/$2 ... whatever2/' > shared2.txt

The result in shared2.txt looks like:


What did I do wrong?


2 Answers 2


Try using double quote instead of single quote:

sed "s/whatever1/$2 ... whatever2/" shared.txt > shared2.txt
  • 3
    My biggest complaint with bash is that simple things like these can trip me up for so long. Thank you!
    – Shadoninja
    May 11, 2016 at 23:37

While using double quotes works, there are certain circumstances where this won't give what you want. For example,

echo '123$tbcd' | sed "s/$t$t//"

(yes, this is somewhat contrived!). You can avoid this by either escaping certain characters:

echo '123$tbcd' | sed "s/\$t$t//"

but it is easy to miss this. The safest way, in my opinion, is to surround the variables with double quotes (so that spaces don't brake the sed command) and surround the rest of the string with single quotes (to avoid the necessity of escaping certain characters):

echo '123$tbcd' | sed 's/$t'"$t"'//'.

Not the answer you're looking for? Browse other questions tagged .