Skip to content

Instantly share code, notes, and snippets.

@lukebayes
Created March 10, 2013 23:18
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 lukebayes/5130955 to your computer and use it in GitHub Desktop.
Save lukebayes/5130955 to your computer and use it in GitHub Desktop.
Simple Bash/Posix find and replace shell script. This script is dangerous and will perform a recursive in-place modification of every file forward of the provided directory. Binary files, hidden files, etc. Use with caution.
#!/bin/bash
die () {
echo >&2 "$@"
exit 1
}
[ "$#" -eq 3 ] || die "3 arguments required ('find', 'replace', dir), $# provided"
MATCH=$1
REPLACE=$2
DIR=$3
echo "Replacing $MATCH with $REPLACE recursively in $DIR with files:"
grep -r --color $MATCH $DIR
echo ""
read -p "Are you sure? [y/n]" -n 1 -r
echo ""
if [[ $REPLY =~ ^[Yy]$ ]]
then
find $DIR -type f -print0 | xargs -0 sed -i s/$MATCH/$REPLACE/g
echo "Replace complete"
else
echo "Aborted find/replace due to confirmation failure."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment