sed substitution and shell variables

Hello!!

Am trying to substitute the value of a shell variable with the value of another shell variable. The values are obtained into the shell variables through some other processing.
for ex.

i've used the follow sed command..

sed "s/$var1/$var2/g"

i've also tried the other alternatives i found searching the threads. But nothing worked.. .
Please help!

did you try this ?

sed -i '' "s/${var1}/${var2}/g" yourfile

I had not tried it earlier, but now i did..

the error am finding is

sed: can't read s///g: No such file or directory

did you specify your filename at the end of the command ?
did you pake sure you didn't forget any simplequote nor double quote ?

for me it works :

$ cat tst
cool
change
Frinto Francis
Frinto cool
change Attitude
/usr/bin
$ var1=cool
$ var2=CEWL
$ sed -i '' "s/${var1}/${var2}/g" tst
$ cat tst
CEWL
change
Frinto Francis
Frinto CEWL
change Attitude
/usr/bin

i've checked every detail of the command and specified it in the same manner..

the error this time is

sed: can't read s/cool/CEWL/g: No such file or directory

the problem is probably the two single quotes after "-i". If i remember correctly "-i" means "change the file in place, instead of writing the results of the substitions to another file". If this is the case the '' is treated as the regex expression and the regex is treated as filename.

It is not a good idea to use the "-i" switch anyways, because firstly you run the risk of changing your original with some unwanted substitution and secondly the "-i"-switch is not supported by most sed-versions and hence your command is not very portable.

My suggestion is to write it this way:

sed "s/${var1}/${var2}/g" /path/to/yourfile | more

Once you are satisfied with the outcome displayed you can replace "| more" by some redirection to a file. Use "mv" to overwrite the original with this file if you want to do so.

@a_ba:

This looks like your variables aren't being expanded at all. Check the spelling of your variables (even capitalization counts, "$a" and "$A" is NOT the same).

A second possible problem is variable scope: Maybe the variables are not set in the environment you (try to) use them but another. Try this to make sure this is not the problem:

var1="<...>"; var2="<...>" ; sed "s/${var1}/${var2}/g" /path/to/yourfile | more

I hope this helps.

bakunin