Skip to content

Instantly share code, notes, and snippets.

@NightMachinery
Forked from hlissner/replace.sh
Last active December 2, 2021 00:13
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NightMachinery/719ec06299c65b5216d551658b78c951 to your computer and use it in GitHub Desktop.
Save NightMachinery/719ec06299c65b5216d551658b78c951 to your computer and use it in GitHub Desktop.
Bulk search & replace with ag (the_silver_searcher)

You can use it like this:

from=str1 to=sth agr path1 path2 ...

Supply no paths to make it use the current directory. Note that ag, xargs, and perl need to be installed and on PATH.

# ag <https://github.com/ggreer/the_silver_searcher>
# from=str1 to=sth agr path1 path2 ...
# backs up to .pbak
comment() {
}
doc() {
}
function agr {
doc 'usage: from=sth to=another agr [ag-args]'
comment -l --files-with-matches
ag -0 -l "$from" "${@}" | pre-files "$from" "$to"
}
pre-files() {
doc 'stdin should be null-separated list of files that need replacement; $1 the string to replace, $2 the replacement.'
comment '-i backs up original input files with the supplied extension (leave empty for no backup; needed for in-place replacement.)(do not put whitespace between -i and its arg.)'
comment '-r, --no-run-if-empty
If the standard input does not contain any nonblanks,
do not run the command. Normally, the command is run
once even if there is no input. This option is a GNU
extension.'
AGR_FROM="$1" AGR_TO="$2" xargs -r0 perl -pi.pbak -e 's/$ENV{AGR_FROM}/$ENV{AGR_TO}/g'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment