Skip to content

Instantly share code, notes, and snippets.

@romanlv
Last active November 15, 2019 20:14
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 romanlv/d808ac17d177d9eda90b899bd666e0e3 to your computer and use it in GitHub Desktop.
Save romanlv/d808ac17d177d9eda90b899bd666e0e3 to your computer and use it in GitHub Desktop.
command to search and replace strings in found files using `ag`
function ag_replace {
if [ -z "$1" -o $# -eq 1 ]; then
echo "Usage: ag_replace FROM_STRING TO_STRING [OPTION]..."
echo
echo "Replace all occurances of FROM_STRING (a sed-compatible regular"
echo "expression) with TO_STRING in all files for which ack-grep matches"
echo "FROM_STRING."
echo
echo "Any additional options are passed directly to ack-grep (e.g.,"
echo " --type=html would only run the substitution on html files)."
return 1
fi
# Escape forward slashes for sed
FROM_STRING=${1/\//\\/}
TO_STRING=${2/\//\\/}
shift 2
ag -l --print0 "$@" "$FROM_STRING" | xargs -0 -n 1 sed -i '' "s|$FROM_STRING|$TO_STRING|g"
}
@romanlv
Copy link
Author

romanlv commented May 24, 2019

example

source ag_replace.sh

ag_replace '"package": "^2.0.1"' '"package": "^2.3.1"'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment