30 April 2009

Unix recursive Find and Replace

find spec ! -regex ".*.svn.*" -type f -exec grep -l "it_should_behave_like" {} \; | xargs sed -i "" "s/it_should_behave_like/#it_should_behave_like/"

Explanation:
  • find spec find in ./spec folfer
  • ! -regex ".*.svn.*" excluding .svn folders
  • -type f only files
  • -exec grep -l "it_should_behave_like" {} \; extra line to grep only files which contain "it_should_behave_like"
  • | xargs sed -i "" pipe to sed editor without creating any backup file (-i)
  • "s/ENTER OLD STRING OR TEXT TO REPLACE/ENTER REPLACEMENT STRING OR TEXT/"

2 comments:

Philippe said...

Hu... that's quite complex.

I use instead:
perl -p -i -e 's/oldstring/newstring/g' `find ./ -name *.html`


Even simpler with zsh:
perl -p -i -e 's/oldstring/newstring/g' **/*

scripter said...

nice information
find some more information about unix find command
http://scripterworld.blogspot.com/2009/07/unix-find-command-with-examples-and.html