You could use find
and perl
(via xargs
):
find /target/directory -type f | xargs perl -pi -e 's/stringtoreplace/replacement/g'
or if you are already in the right directory
find . -type f | xargs perl -pi -e 's/stringtoreplace/replacement/g'
and if you only want to replace in, say, html files:
find . -type f -name '*html' | xargs perl -pi -e 's/stringtoreplace/replacement/g'
You don't have to use perl of course, any tool that performs search and replace operations will do, and not doubt there are several available that are less resource hungry than starting perl (which is this case is a sledge-hammer to crack a nut, but it is an example I've had stored for ages and I've no reason to find a more efficient version). My original source for the "trick" is http://oreilly.com/pub/h/73
You can use all the options in which-ever tool you choose, so in this case the full power of Perl's regular expressions. The page linked to above has more examples, including how to search in a case in-sensitive manner.
4You can use
sed -i 's/string/replacement/g'
in place ofperl
in that command. If you're using GNUsed
, just add ani
after theg
to make it case insensitive. – Paused until further notice. – 2010-07-10T21:20:24.5434Also, unless you know what the names in the directories are like, you should really use the -print0 argument to find, and the -0 argument to xargs. A file with a carriage return, space, or tab in the name could cause you problems otherwise. – Slartibartfast – 2010-07-11T02:51:48.757
1Good point on -print0/-0 - I always avoid such characters in names but even if you do you still need to be careful because others may not. – David Spillett – 2010-07-11T12:53:21.137