@madpilot makes

Global search and replace using the command line

If you have ever used Dreamweaver, you are probably familiar with the Global Search and Replace feature, which allows you to search and replace amongst all files with in a site, which can be very handy if you are doing a static site. If you are too hard core for Dreamweaver though, and you spend your whole day buried in a terminal window, how can you achieve the same thing? By this piece of bash-trickery, that’s how:

find . | grep html | xargs -t -I {} sh -c "cat {} | sed 's/Stuff to find/Replace with this/' > {}"
  1. find . – find all the files from the current directory down
  2. grep html – filters the output to include only filesnames with html in them
  3. xargs -t -I {} sh -c – pumps the file names into the cat command, but also sets a variable called {} that holds the filename
  4. sed ‘s/Stuff to find/Replace with this/’ – just a search and replace
  5. > {} – save the output back to the original file name
  6. A word of warning though, leave the last bit off until you are sure your output is correct, because there is no undo feature :)

1 comment

  1. One of my favorite variations of this is to use find with perl:

    find . -name '*.html' -exec perl -pi -e 's/Stuff to find/Replace with this/g' {} ;

    If you change the switches to perl to -pi.bak -e it will append ".bak" to the original files and then create new files with the replacements done to them.

Leave a comment