Passing a variable to sed
80,750
Solution 1
Try using double quote instead of single quote:
sed "s/whatever1/$2 ... whatever2/" shared.txt > shared2.txt
Solution 2
While using double quotes works, there are certain circumstances where this won't give what you want. For example,
t="bcd"
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"'//'.
Related videos on Youtube
Author by
user2013619
Updated on September 18, 2022Comments
-
user2013619 almost 2 years
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:...$2....
What did I do wrong?
-
Shadoninja about 8 yearsMy biggest complaint with bash is that simple things like these can trip me up for so long. Thank you!