To replace a text in a file, you can invoke sed as in the following example :

1
% cat file.txt | sed -e 's/text/replacement/g' > result.txt

This will change all the occurences of “text” to “replacement” in “file.txt” and output the result in “result.txt”

Note : As suggested by Matthias from adminlife in the comments, if you wanted to do “in place” text replacement (that is modify the file without a temporary file in between), you can do the following :

1
sed -i ’s/text/replacement/g’ file.txt

For more complicated text manipulations you might consider moving to Perl, but sometimes you don’t need the sledge-hammer :-)

October 20, 2007 at 8:59 pm by Stephane Kattoor
Category: Systems
Tags: , , ,