Have sed ignore non-matching lines

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'

Additionally, you can use a preceding matching pattern /match only these lines/ to only apply the replacement command to lines matching this pattern.

This gives:

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

e.g.:

# replace all occurrences of `bar` with `baz`
sed -n 's/bar/baz/p'

# replace `bar` with `baz` only on lines matching `foo`
sed -n '/foo/ s/bar/baz/p'

See also this other answer addressing Rapsey’s comment below on multiple replacements

Leave a Comment