How can I make sed
filter matching lines according to some expression, but ignore non-matching lines, instead of letting them print?
As a real example, I want to run scalac
(the Scala compiler) on a set of files, and read from its -verbose
output the .class
files created. scalac -verbose
outputs a bunch of messages, but we're only interested in those of the form [wrote some-class-name.class]
. What I'm currently doing is this (|&
is bash 4.0's way to pipe stderr to the next program):
$ scalac -verbose some-file.scala ... |& sed 's/^\[wrote \(.*\.class\)\]$/\1/'
This will extract the file names from the messages we're interested in, but will also let all other messages pass through unchanged! Of course we could do instead this:
$ scalac -verbose some-file.scala ... |& grep '^\[wrote .*\.class\]$' | sed 's/^\[wrote \(.*\.class\)\]$/\1/'
which works but looks very much like going around the real problem, which is how to instruct sed
to ignore non-matching lines from the input. So how do we do that?
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 printp
flag which tells sed to print what is matchedThis gives:
sed -n 's/.../.../p'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With