Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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
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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .