0

In vi editor, I understand the following line does a search and replace of all occurrences in a file:

:%s/search_string/replacement_string/g

How can I search a string across all files in all subdirectories (entire folder tree) and do a replace in all those files (with occurrences of search string)?

m.beginner
  • 389
  • 2
  • 18

1 Answers1

0

I prefer to do this outside of vim, with sed:

find . -type f -name "*" | xargs sed -i "s/search_string/replacement_string/g"

will replace all instances of search_string with replacement_string in all files in and under the current directory.

OSX (BSD sed):

find . -type f -name "*" | xargs sed -i '' "s/search_string/replacement_string/g"

Note the extra empty string arg sed -i '' "s/...

Bonus: I often find it useful to search/replace interactively (with y/n prompt per replacement) across all files. Vim handles this beautifully:

for filename in $(find . -type f -name "*"); do vim -c "%s/search_string/replacement_string/gc" -c "wq" "${filename}"; done

Credit to all those that have answered this question in the past and helped me with countless refactors. Search and replace in Vim across all the project files

evnp
  • 191
  • 1
  • 6