In the following example, sed
matches lines starting with an a
or a c
and prints the first character of that line (a
or c
):
$ echo "ag
bh
ci
dj
ek
fl" | sed 's/\(a\|c\)./\1/' # Matches lines starting with 'a' or 'c'.
output:
a
bh
c
dj
ek
fl
However, the lines that do not match the pattern are also printed out. How do I tell sed
to omit the lines that doesn't match the pattern? I can obtain the desired effect by combining it with grep
(as follows) but I would like to know if sed
can achieve that "by itself".
$ echo "ag
bh
ci
dj
ek
fl" | grep '[ac]' | sed 's/\(a\|c\)./\1/'
output:
a
c
Best Answer
Use the
no-print
flag (-n
) and explicitly print successful substitute commands (s///p
):