Skip to content

Instantly share code, notes, and snippets.

@troelskn
Created July 3, 2009 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save troelskn/140084 to your computer and use it in GitHub Desktop.
Save troelskn/140084 to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# find and replace by regexp in many files
PRUNE=""
REPLACE=""
print_usage() {
echo "USAGE: $(basename $0) [--prune EXTENSIONS] [--replace REPLACE] SEARCH"
echo " EXTENSIONS Comma separated list of file extensions to ignore"
exit 1
}
while true
do
case "$1" in
--prune) PRUNE="$PRUNE,$2" ; shift 2 ;;
--replace) REPLACE="$2" ; shift 2 ;;
--help) print_usage ;;
--) shift ; break ;;
*) break ;;
esac
done
if [ $# -eq 0 ]
then
print_usage
fi
if [ $PRUNE ];
then
FIND_ARGUMENTS=`echo $PRUNE | sed "s/,*\([^,]*\)/ -o -name '*\1'/g"`
else
FIND_ARGUMENTS=""
fi
FIND_ARGUMENTS="-name .svn $FIND_ARGUMENTS"
FIND_COMMAND="find . \( $FIND_ARGUMENTS \) -prune -o -type f -print0"
if [ "$REPLACE" == "" ];
then
eval $FIND_COMMAND | xargs -0 grep --with-filename --line-number --ignore-case --color='always' "$1" | sed -e 's/^\([^:]*\):\([^:]*\):/\1 : \2 :/g'
else
eval $FIND_COMMAND | xargs -0 grep --with-filename --line-number --ignore-case --files-with-matches "$1" | xargs sed -i -e "s/$1/$REPLACE/g"
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment