Replacing patterns in a file

Hi Everybody,

Can we replace the contents of a file without using a temporary file.

For ex:
I need to relpace the value "old" with "new", I can do it using the sed replace pattern, but I do not want to use a temporary file.

Also, from the questions posted in the past I could see a fantastic command to do this
printf '1,$ s/old/new/g\nw! samp.txt\nq!'| ex - samp.txt

But, with the same command I am not able to replace the value of a variable
For ex: var1='new'
printf '1,$ s/new/$var1/g\nw! samp.txt\nq!'| ex - samp.txt

The above command doesn't replace the value of the variable.

You can use sed to replace stings without using a temp file using its -i (edit in place) flag.

Shell variables are not interpreted inside single quotes. You should use double quotes or terminate the single quote before $var and start it after $var.

$ printf '1,$ s/new/'$var1'/g\nw! samp.txt\nq!'| ex - samp.txt
$ 
$ echo "this is old data">f1
$ cat f1
this is old data
$ 
$ perl -pi.bak -e 's/old/new/g' f1
$ 
$ ## backup
$ cat f1.bak
this is old data
$ ## new
$ cat f1
this is new data
$ 

tyler_durden

Hi agn,
Thanks for the input, it is working