0

Currently I find and replace using the following:

ack -l oldstring | xargs sed -i '' -e s/oldstring/newstring/g

Is there a way to do this without having to type out oldstring more than once? This is what I'm trying that does not work:

ack -l oldstring | xargs sed -i '' -e s/{}/newstring/g
YPCrumble
  • 26,610
  • 23
  • 107
  • 172
  • Does this help? http://stackoverflow.com/questions/14402949/how-to-use-xargs-with-sed-in-search-pattern Or are you in a catch-22? – stevesliva Mar 06 '17 at 21:38
  • @stevesliva the issue is that these are for one file at a time (file.txt) in the examples. In my case ack -l returns a list of file names that all contain oldstring, all of which I want to apply the find and replace command to. – YPCrumble Mar 08 '17 at 02:30

1 Answers1

0

I finally decided to create two bash functions to save typing:

# Function to find and replace.
function ags {
  #!/bin/bash
  ag -l "$1" | xargs sed -i '' -e "s/$1/$2/g";
}
# Function to delete any lines that contain a string.
function agd {
  #!/bin/bash
  ag -l "$1" | xargs sed -i '' -e "/$1/d";
}
YPCrumble
  • 26,610
  • 23
  • 107
  • 172