Have sed ignore non-matching lines

Solution 1:

If you don't want to print lines that don't match, you can use the combination of

  • -n option which tells sed not to print
  • p flag which tells sed to print what is matched

This gives:

sed -n 's/.../.../p'

Solution 2:

Another way with plain sed:

sed -e 's/.../.../;t;d'

s/// is a substituion, t without any label conditionally skips all following commands, d deletes line.

No need for perl or grep.

(edited after Nicholas Riley's suggestion)

Solution 3:

Use Perl:

... |& perl -ne 'print "$1\n" if /^\[wrote (.*\.class)\]$/'

Solution 4:

Rapsey raised a relevant point about multiple substitutions expressions.

  • First, quoting an Unix SE answer, you can "prefix most sed commands with an address to limit the lines to which they apply".
  • Second, you can group commands within curly braces {} (separated with a semi-colon ; or a new line)
  • Third, add the print flag p on the last substitution

Syntax:

sed -n -e '/^given_regexp/ {s/regexp1/replacement1/flags1;[...];s/regexp1/replacement1/flagsnp}'

Example (see Here document for more details):

  • Code:

    sed -n -e '/^ha/ {s/h/k/g;s/a/e/gp}' <<SAMPLE
    haha
    hihi
    SAMPLE
    
  • Result:

    keke