Awk/Sed: How to do a recursive find/replace of a string?

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


13 points

I am trying to replace specific text within several files (maybe around 200 files). Is there a way that I could this without having to replace the text manually.

I am actually trying to change the IPs in several httpd.conf, eg. 192.168.0.5 to 192.168.0.10. I have googled and some of the sites suggested using grep and awk, but no specific help was found by me.

Any help is greatly appreciated. Thanks.



4 points

You can do

Code:
sed 's/original_string/new_string/' file1 file2 file3 ...

If the strings contain the character / you can use any other character
for delimiter.

On second thought this will send all the output to the screen.
So I guess you should do

Code:
sed 's/original_string/new_string/' file > tmp_file
mv tmp_file file

and repeat this for every file you want changed.

ranipoojax's picture
Created by ranipoojax
6 points

You can use Perl and Find as following:

perl -p -i -e 's/oldstring/newstring/g' `find ./ -name *.html`

Anonymous's picture
Created by Anonymous
1 point

in lieu of writing to a tmp file and moving it afterwards to the original file, do an in-place edit:

sed -i 's/original_string/new_string'

You might want to combine it with find as this:
find /dir -name \*.ext | xargs sed -i 's/original_string/new_string'

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.