Skip to content

Instantly share code, notes, and snippets.

@lelandbatey
Forked from adamryman/ag-replace.sh
Last active August 17, 2022 19:36
Show Gist options
  • Save lelandbatey/6c0b589b845891c673c1cc7e73e02ab3 to your computer and use it in GitHub Desktop.
Save lelandbatey/6c0b589b845891c673c1cc7e73e02ab3 to your computer and use it in GitHub Desktop.
`ag --literal --case-sensitive "THIS"`, I want to replace all occurrences of "THIS" with "THAT". `Just do ag-replace "THIS" THAT"`
#!/bin/bash
usage() {
echo "Usage: $(basename $0) \"THIS\" \"THAT\"";
echo "Replaces all instances of THIS with THAT in all files which contain THIS."
echo "Additionally, prints each file as that file is modified"
exit 1;
}
replace() {
excaped1=$(echo "$1" | sed -e 's/[\/&]/\\&/g');
excaped2=$(echo "$2" | sed -e 's/[\/&]/\\&/g');
# list only the file names of files with this literal string, case sensitive
files=$(ag "$1" --literal --case-sensitive --files-with-matches)
echo "$files" | while read line; do
echo "$line"
sed -i "s/$excaped1/$excaped2/g" "$(pwd)"/"$line";
done;
}
if [ "$#" -ne 2 ]; then
usage;
exit 1;
else
replace "$@";
fi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment