LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Replace contents of a file (https://www.linuxquestions.org/questions/linux-newbie-8/replace-contents-of-a-file-448384/)

shiroh_1982 05-25-2006 06:41 AM

Replace contents of a file
 
Hi,

I want to replace the contents of a file.I tried using :
sed 's/01514581/01514582/' $p
where 01514581 is the original value
01514582 is the replaced value
$p is the file name (captured in a variable)..

The output does not recognise $p

If you give :
sed 's/01514581/01514582/' test
where 'test' is the filename

then the output is not getting saved into the file 'test'..

Kindly let me know how i can do this.
Thanks

marozsas 05-25-2006 07:25 AM

Quote:

Originally Posted by shiroh_1982
If you give :
sed 's/01514581/01514582/' test
where 'test' is the filename

then the output is not getting saved into the file 'test'..

The editing is not in place. I mean, the original file remains intact and a new one must be created. sed is supposed to be used as a "filter", not as a in-place editor.

Create a copy of test, use the copy as input to sed, and send the modified stream to test.
Code:

$ cp test test.original
$ sed 's/01514581/01514582/' test.original > test


Quote:

Originally Posted by shiroh_1982
The output does not recognise $p

Thats mean $p was not set in the proper way. If you are using bash:
Code:

$ p="test"
$ echo $p
test
$ q="${p}.original"
$ sed 's/01514581/01514582/' $q > $p


pronoy 05-25-2006 07:29 AM

Quote:

Originally Posted by shiroh_1982
Hi,

I want to replace the contents of a file.I tried using :
sed 's/01514581/01514582/' $p
where 01514581 is the original value
01514582 is the replaced value
$p is the file name (captured in a variable)..

The output does not recognise $p

Sorry I could not get the problem here

Quote:

If you give :
sed 's/01514581/01514582/' test
where 'test' is the filename

then the output is not getting saved into the file 'test'..

Kindly let me know how i can do this.
Thanks
you can do it in 2 ways:

1.
$ sed 's/01514581/01514582/' test >/tmp/test.tmp
$ mv /tmp/test.tmp test
2. perl -pi -e 's/01514581/01514582/' test

Hope this works.

spirit receiver 05-25-2006 07:50 AM

Quote:

Originally Posted by shiroh_1982
the output is not getting saved into the file 'test'..

"sed -i 's/01514581/01514582/' test" will also do the trick.


All times are GMT -5. The time now is 09:06 AM.