Solved Substituting environment variables in sed script

Is it possible to substitute environment variables in a sed script?

Can I expect to be able to substitute $A for $B in a file using

sed s/$A/$B/ somefile

eg

Code:
echo 'aaa' > aaa
echo 'bbb' > bbb
A=`cat aaa`
B=`cat abc`
echo $A $B
sed s/{\$A}/{\$B}/ aaa
cat aaa
 
No, regular old-fashioned sed won't do that. It will see the strings "$A" and "$B" in your example. It's possible that the gnu version of sed has some extension for it, but I'm too lazy to look.

But there is an easy way to do this: Have the shell do the substitution. For example "sed s/$A/$B/ aaa". In your example, sed would see the first argument "s/aaa/bbb/".

The only problem with this is: the moment either A or B are either empty, or zero length, or contain a space, or a newline, or any other crazy edge condition, this will break spectacularly. The rules for quoting things in shells are bizarre and complex, so you better learn them.
 
No, regular old-fashioned sed won't do that. It will see the strings "$A" and "$B" in your example. It's possible that the gnu version of sed has some extension for it, but I'm too lazy to look.

But there is an easy way to do this: Have the shell do the substitution. For example "sed s/$A/$B/ aaa". In your example, sed would see the first argument "s/aaa/bbb/".
Looks like I was anticipating problems which didn't exist...

Code:
echo 'aaa' > aaa
echo 'bbb' > bbb
A=`cat aaa`
B=`cat abc`
echo $A $B
cat aaa
sed -i '' s/$A/$B/ aaa
cat aaa


Much simpler than I thought.
 
Back
Top