Created
December 28, 2023 05:50
-
-
Save markburns/0aee0f533b414f6732322ae738b3d4c8 to your computer and use it in GitHub Desktop.
replace
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
#!/bin/bash | |
# Find and replace by a given list of files supporting multiline matching. | |
# | |
# Usage: replace "find_pattern" "replace_with" **/*.rb | |
find_this="$1" | |
shift | |
replace_with="$1" | |
shift | |
if command -v rg &>/dev/null ; then | |
items=$(rg -l --color never "$find_this" "$@") | |
else | |
items=$(ag -l --nocolor "$find_this" "$@") | |
fi | |
temp="${TMPDIR:-/tmp}/replace_temp_file.$$" | |
IFS=$'\n' | |
for item in $items; do | |
# Use sed to perform multiline replacement | |
sed -z "s/$find_this/$replace_with/g" "$item" > "$temp" && mv "$temp" "$item" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment