Skip to content

Instantly share code, notes, and snippets.

@markburns
Created December 28, 2023 05:50
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 markburns/0aee0f533b414f6732322ae738b3d4c8 to your computer and use it in GitHub Desktop.
Save markburns/0aee0f533b414f6732322ae738b3d4c8 to your computer and use it in GitHub Desktop.
replace
#!/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