Skip to content

Instantly share code, notes, and snippets.

@kates
Last active August 31, 2019 05:22
Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save kates/5915285 to your computer and use it in GitHub Desktop.
Save kates/5915285 to your computer and use it in GitHub Desktop.
bulk search and replace with the silver searcher, awk, sed and xargs
ag "sometext" --nogroup | awk '{print substr($1,1,index($1,":")-1);}' | xargs -I {} sed -i .bak -e 's/sometext/anothertext/g' {}
@pencilcheck
Copy link

Is it possible to make it into a script with arguments?
The default argument names are conflicting with the awk commands...

@charlesoconor
Copy link

Yes. The string passed to sed is single quoted so it shouldn't be an issue. The script will just be a little harder to read.

ag "$1" --nogroup | awk '{print substr($1,1,index($1,":")-1);}' | xargs -I {} sed -i '.back' -e "s/$1/$2/g" {}

@nayshawndanner
Copy link

Here's a small improvement:
ag $1 --files-with-matches | xargs -I {} sed -i '.back' -e "s/$1/$2/g" {}

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