Find and replace text in files with the silver searcher and sed
Asked Answered
A

1

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.

Agitprop answered 3/8, 2018 at 20:20 Comment(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/.../' ?Foregut
My bad, I meant -l. Updated in question.Agitprop
F
14

xargs is the magic you are looking for:

ag -l 'foo'|xargs sed -i 's/foo/abcd/g'
Foregut answered 3/8, 2018 at 20:26 Comment(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.Agitprop
@Agitprop 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.Foregut
@Agitprop Sed on macOS requires an argument to the -i option, see #5694728Rois
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.Agitprop

© 2022 - 2024 — McMap. All rights reserved.