Find and replace text in multiple files

As always, back up all files before doing this. In the regexp, remember to escape the necessary characters, e.g. slashes.

Use the find command to list all files matching the criteria and pipe through xargs to perl to find and replace the text with a regular expression (regexp) match. This example will replace oldtext with newtext in all .html files:

find . -name '*.html' | xargs perl -pi -e 's/oldtext/newtext/g'

Dealing with spaces in the filename

The following examples are more complex, but they do handle spaces in the filename (the sed line adds double quotes around the filenames). Files that have their text replaced are backed up with a .bak extension.

Find *.*html files that contain myDiv412 and delete the matching line (whole line match):

find ./ -name "*.*html" -exec grep myDiv412 -l {} \; | sed -e 's/.*/"&"/' | xargs sed -e '/^the line to match*/d' -i.bak

Find *.*html files that contain myDiv412 and delete the matching line (partial line match):

find ./ -name "*.*html" -exec grep myDiv412 -l {} \; | sed -e 's/.*/"&"/' | xargs sed -e '/^.*part of the line to match.*/d' -i.bak

Find .html files that contain myDiv412 and replace all instances of foo with bar. Note: Must be tested.

find ./ -name "*.*html" -exec grep myDiv412 -l {} \; | sed -e 's/.*/"&"/' | xargs sed -e 's/foo/bar/g' -i.bak

References

Last modified: 23/09/2008 Tags: , ,

Go to top

This website is a personal resource. Nothing here is guaranteed correct or complete, so use at your own risk and try not to delete the Internet. -Stephan

Site Info

Privacy policy

Go to top