6

Heck I just can't remember ... I recently had a cool way to use ag with sed to do find and replace. The gist was simple, something like:

ag foo -l |  ... magic here ...   sed 's/foo/bar/g'

That doesn't work, but you might just know what does. Thanks!

PS. Three cheers for the Silver Searcher.

2
  • I don't know what do you want.. -L gives not-match filenames, what does your magic do there??? there is no "foo" in those files, you sed 's/foo/.../' ?
    – Kent
    Commented Aug 3, 2018 at 20:23
  • My bad, I meant -l. Updated in question.
    – Robert
    Commented Aug 3, 2018 at 20:24

1 Answer 1

14

xargs is the magic you are looking for:

ag -l 'foo'|xargs sed -i 's/foo/abcd/g'
4
  • I get an error with your suggestion: sed: 1: "AppMain/State.elm": invalid command code A. This is the first file my text is found in. BTW I am on a Mac.
    – Robert
    Commented Aug 3, 2018 at 20:33
  • 1
    @Robert read my answer carefully, do copy and paste, replace the foo and bar by your values. you forgot the important s. if you are on a mac (bsd sed), you may need some option like -E, I don't know, read the man page.
    – Kent
    Commented Aug 3, 2018 at 20:44
  • 3
    @Robert Sed on macOS requires an argument to the -i option, see stackoverflow.com/questions/5694228/… Commented Aug 3, 2018 at 21:09
  • 1
    Yes, thanks Benjamin, Mac (BSD) sed is a bit different. As it explains in the link you posted, one way to make it work is to use the -i.bak option rather than just -i. As it also explains, the other way is to install Gnu sed with homebrew.
    – Robert
    Commented Aug 4, 2018 at 5:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.