Batch search and replace across multiple files seems to come up a lot. It’s good to know a quick and simple way to do this on text files.
Problem
Suppose you have 100 XML files and you want to add an attribute to one of the elements.
Current XML: <document author=”mark”>
Desired XML: <document date=”2008-08-08″ author=”mark”>
Any XML or even text editor can do search and replace on this easily through the GUI. But if you have 100 XML files that need the same thing done, you need a quick way to do this in batch.
Solution
We’ll write a shell script to read in all 100 XML files, do a search and replace to add the new attribute, and create a new version of each modified XML file in a new directory.
To run the shells script, you need either:
- Unix, Linux, or Mac OS X
- or Cygwin Bash Shell for Windows
Here is the batch search and replace shell script:
for x in *.xml; do sed -e 's/<document/<document date="2008-08-08"/g' < $x > tmp/$x; done
Make sure the directory tmp/ already exits; that is where all your modified files will go.
That’s it. Just a simple for loop and a search and replace command. Next time you need to change something across multiple documents, write a simple script instead of doing it manually.