Search code examples
sedpipeackag

How can I find and replace with a variable using a list of filenames piped to sed?


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

Solution

  • 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";
    }