Skip to content

Instantly share code, notes, and snippets.

@lelandbatey
Created August 17, 2022 20:03
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 lelandbatey/856dc63e9c8cf7e74e740b62a7c64859 to your computer and use it in GitHub Desktop.
Save lelandbatey/856dc63e9c8cf7e74e740b62a7c64859 to your computer and use it in GitHub Desktop.
Replace all occurrences of "THIS" with "THAT" in all files in current directory and descendants
#!/bin/bash
# Originally based on ag-replace.sh:
# https://gist.github.com/adamryman/1de22e36a14c29da2f41c8512cb86b6d
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() {
escaped1=$(echo "$1" | sed -e 's/[\/&]/\\&/g');
escaped2=$(echo "$2" | sed -e 's/[\/&]/\\&/g');
# list only the file names of files with this literal string, case sensitive
files=$(rg "$1" --fixed-strings --case-sensitive --files-with-matches)
echo "$files" | while read line; do
echo "$line"
sed -i "s/$escaped1/$escaped2/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