Skip to content

Instantly share code, notes, and snippets.

@tribou
Last active July 26, 2016 10:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tribou/4cf54ddafef1a331efd8 to your computer and use it in GitHub Desktop.
Save tribou/4cf54ddafef1a331efd8 to your computer and use it in GitHub Desktop.
Bash script to find and replace a string recursively with file and directory exclusions
#!/bin/bash -l
# Recursively performs a perl replace on files in current or specified directory
# ...took me all afternoon to get it right.
# Examples:
# replace 's/stringtofind/stringtoreplacewith/g'
# replace 's/foo/bar/g' path/to/dir
replace() {
usage='Usage: replace PATTERN [directory]'
search_dir='.'
# Return usage if 0 or more than 2 args are passed
if [ $# -eq 0 ] || [ $# -gt 2 ]
then
echo "$usage"
return 1
fi
# Optional second arg
if [ $# -eq 2 ]
then
# Remove trailing slash if any
search_dir=`echo "$2" | sed 's/\/$//'`
fi
# Excludes files named "bundle*.js" as well as node_modules, .git, and .svn directories
find \
"$search_dir" \
-type f \
! -name "bundle*.js" \
! -path "*/node_modules/*" \
! -path "*/.git/*" \
! -path "*/.svn/*" \
-exec perl -p -i -e "$1" {} \;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment