Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
share|improve this question
    
It doesn't matter for what you really wanted to know, but your pattern should start with ^ so it's anchored to the beginning of the line. As coded, it would match an a or c anywhere in the line as long as it's not the last character. –  Joe Jan 29 '13 at 3:42

1 Answer 1

up vote 12 down vote accepted

Use the no-print flag (-n) and explicitly print successful substitute commands (s///p):

 sed -n 's/\(a\|c\)./\1/p'
share|improve this answer
    
Great, that worked. Thanks! –  freitass Jan 24 '13 at 11:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.