There are many and varied ways of searching for and replacing strings in files, here are three.
find . -name *.html -type f -exec sed -i \
-e 's/string1/string2/' {} \;
This will use find to locate all files with the html extension in the directory it’s run in and any descendent directories, once it finds a file it runs sed to replace inline any occurrences of string1 with string2. Combining find and sed probably gives you the greatest flexibility and power in searching and replacing without having to know a great deal about programming.
perl -pi -e 's/string1\.$/string2\./' *.html
Perl inline search and replace, you’ll find a full explanation of this and more complex variations on this in the Debian Administration article Search and replace across many files with a perl one-liner, the above is the simple case from the article.
It’s good, but to get any real value from the knowledge you really need to learn perl.
If you want to do the same thing in Ruby you might try:
ruby -p -i.bak -e 'gsub("string1", "string2")' \
*.html
Again, that won’t help you do much else unless you learn at least a little Ruby.
rpl -R -xhtml string1 string2 *
RPL: the really easy way. It’s a package on Debian stable you may have to apt-get but from my point of view it’s perfect for people who aren’t that confident with things like find or perl, not everyone has the inclination to go learn such things and the whole team needs to be effective.
The RPL man page is pretty straight forward, the above line will search recursively for all files with an extension html (-x option) and replace string1 with string2.
«0 CommentsApril 26, MMVI»
You've arrived at the homepage of Stephen Stewart. The archive is available here for those who want it. This site is happily hosted by Dreamhost. Click for more?
More!? OK then, but I can't help feeling that this will be a disappointment to you.
I work as a web designer in Belfast, and I live by the sea in a shoe. You can see me here, doing my livejournal pose as idoru called it. If you need to you can email me at carisenda -at- gmail -dot- com.