Using sed and grep/egrep to search and replace

Ori picture Ori · Jul 23, 2009 · Viewed 126.2k times · Source

I am using egrep -R followed by a regular expression containing about 10 unions, so like: .jpg | .png | .gif etc. This works well, now I would like to replace all strings found with .bmp

I was thinking of something like

egrep -lR "\.jpg|\.png|\.gif" . | sed "s/some_expression/.jpg/" file_it_came_form

so the issue here is how do I do a similar union regular expression in sed and how do I tell it to save the changes to the file that it got the input from.

Answer

David Schmitt picture David Schmitt · Jul 23, 2009

Use this command:

egrep -lRZ "\.jpg|\.png|\.gif" . \
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'
  • egrep: find matching lines using extended regular expressions

    • -l: only list matching filenames

    • -R: search recursively through all given directories

    • -Z: use \0 as record separator

    • "\.jpg|\.png|\.gif": match one of the strings ".jpg", ".gif" or ".png"

    • .: start the search in the current directory

  • xargs: execute a command with the stdin as argument

    • -0: use \0 as record separator. This is important to match the -Z of egrep and to avoid being fooled by spaces and newlines in input filenames.

    • -l: use one line per command as parameter

  • sed: the stream editor

    • -i: replace the input file with the output without making a backup

    • -e: use the following argument as expression

    • 's/\.jpg\|\.gif\|\.png/.bmp/g': replace all occurrences of the strings ".jpg", ".gif" or ".png" with ".bmp"