Last active
July 4, 2023 12:47
-
-
Save io41/53838ecfa49149d9ead8c7d80c7f3552 to your computer and use it in GitHub Desktop.
ripgrep (rg) replace all files inplace, just like sed -i
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
# install ripgrep & moreutils (for the sponge tool) See https://www.putorius.net/moreutils.html | |
# On mac: brew install moreutils ripgrep | |
# Source this file in your zsh config by adding `source .rgr.zsh` to your .zshrc | |
function rgr() { | |
local context_lines=2 | |
local search="$1" | |
local replace="$2" | |
shift 2 | |
if [[ "$replace" = "" ]]; then | |
cat <<EOF | |
ripgrep replace | |
Usage: | |
rgr 'search pattern' 'replace text' <RIPGREP OPTIONS> | |
Examples: | |
# passes -F to rg to tell it to treat the search pattern as a fixed string | |
rgr 'my (fixed) string' 'a new string' -F | |
# use rg's --glob options to search only *.hcl files but not *.lock.hcl files. | |
rgr 'ref=1.4.2' 'ref=1.5.2' --glob '*.hcl' --glob '!*.lock.hcl' | |
# use matched groups from your search pattern in the replace string | |
rgr 'ref=(\w+).(\w+).(\w+)' 'major=${1}, minor=${2}, patch=${3}' | |
EOF | |
return 1 | |
fi | |
echo | |
echo "Searching for files & replacements..." | |
echo | |
rg "$search" --passthru -r "$replace" --files-with-matches -0 "$@" | xargs -0 rg "$search" --context $context_lines -r "$replace" --with-filename "$@" | |
if [ "$?" = 0 ]; then | |
echo | |
read -q '? Make above replacements? Press (y)es to continue > ' | |
continue=$? | |
else | |
echo "Nothing found to replace" | |
return 2 | |
fi | |
[[ "$continue" = 0 ]] || return 1 | |
while IFS= read -r -d $'\0' file; do | |
echo | |
echo "replacing $file..." | |
rg "$search" --passthru -r "$replace" "$@" "$file" | sponge "$file" | |
done < <(rg "$search" --passthru -r "$replace" "$@" --files-with-matches -0) | |
echo Done | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment