Tuesday, February 16, 2016

How to find and replace text in files recursively from terminal

Search command

find . -name "*.xml" -exec grep -r "4.4.7" {} +

Ex:
Search all xml files containing the string "4.4.7"

             find . -name "pom.xml" -exec grep -r "4.4.7" {} +

Replace command

find <mydir> -name <filetype> -exec sed -i 's/<oldString>/<newString>/g' {} +

-to include all files types
      use -type f instead -name or exclude the filter.

Ex:

Old string: 4.4.7-SNAPSHOT
New string: 4.4.7

            find . -name "pom.xml" -exec sed -i 's/4\.4\.7-SNAPSHOT/4.4.7/g' {} +

Note: When using sed, search string is sensitive to regular expression. Keep in mind to use the escape characters where necessary.