replace snippets

Recursive find and replace on OSX/Linux

Tagged search, replace, sed, osx  Languages bash

Search and replace XXX with YYY in all files:

perl -e "s/XXX/YYY/g;" -pi $(find . -type f)

Troubleshooting

If you get this error:

zsh: argument list too long: perl

Your argument list is clearly too long. Try this instead, or use xargs:

find . \
   -type f \
   -exec perl -i -pe's/XXX/YYY/g' {} +

Search and Replace with Sed

Using sed is more complicated, but this should at least work on Linux:

# Find, backup and replace
find . -name "*.rb" -print | xargs sed -i.bak 's/XXX/YYY/g'
# Delete backup files
find . -name '*.bak' -type f -delete

Reference.

Also see: https://snippets.aktagon.com/snippets/861-search-and-replace-file-contents-and-file-names

Search and replace file contents and file names

Tagged bash, find, replace, search, zsh  Languages bash

Search and replace file contents

# Replace Tree with Trees
# NOTE: If you want to backup the files, change -i '' to -i (without empty string)
grep -rl Tree . |xargs sed -i '' -e 's/Tree/Trees/'

Search and replace of file names

find . -name '*observation*' -exec bash -c 'mv $0 ${0/observation/condition}' {} \;

References https://www.commandlinefu.com/commands/matching/search-replace/c2VhcmNoIHJlcGxhY2U=/sort-by-votes