Last active
July 26, 2016 10:32
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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