2

I have the following data from which I mean to extract only those lines which contain "bb" only. Not "b" or "bbb" or anything else just "bb".

abb
abbb
aabbcc
aabab
abbbbc

Now when I use the following combination of commands-:

cat file1 | grep "bb[^b]

I am getting the output as all the lines in my sample file-:

abb
abbb
aabbcc
aabab
abbbbc

The expected I want is -:(The lines that contain only "bb")

abb
aabbcc

What is the regular expression that can achieve this ?

abbbabb is not valid. I am looking for lines that contain only bb and no other pattern of b. The line will contain only two, consecutive b and no other b characters at all.

9
  • Is this a valid result? abbbcbb ?? Nov 23, 2014 at 13:53
  • @KasiyA No. Only lines that contain bb.
    – Sreyan
    Nov 23, 2014 at 13:55
  • @KasiyA Thanks for pointing that out. I am looking for a regex that filters lines that contain only bb or pairs of bb
    – Sreyan
    Nov 23, 2014 at 13:57
  • what exactly about pair of bb? Does bbabb is valid and abbacbbcabb is not valid in your case? hard to understand. Please edit your question to including all possible ways that you want to get. your input example is not clear and not enough good. Nov 23, 2014 at 14:01
  • 2
    Then you could use this grep '^[^b]*bb[^b]*$' file already mentioned by PM. Nov 23, 2014 at 14:26

2 Answers 2

3

I guess the most straight-forward way is:

grep '^[^b]*bb[^b]*$' file1

Btw, for commands like grep that accept a file name argument it's more efficient to do

grep '^[^b]*bb[^b]*$' file1

or

grep '^[^b]*bb[^b]*$' < file1

(the latter working if no file argument is supported, too)

than

cat file1 | grep '^[^b]*bb[^b]*$'

and often more flexible.

7
  • echo ababba | grep '^[^b]*bb[^b]*$' Nov 23, 2014 at 12:43
  • Or correct it :)
    – terdon
    Nov 23, 2014 at 12:48
  • @terdon: If I understand the OP "bbaa" should be printed.
    – PM 2Ring
    Nov 23, 2014 at 12:54
  • 1
    @HaukeLaging: I'm not sure from the OP if "ababba" is acceptable or not. Yes, it contains bb, but it also contains an additional b. So I might wait for clarification before modifying / removing my answer.
    – PM 2Ring
    Nov 23, 2014 at 12:55
  • So it should, sorry, wrong example. I was thinking of something like echo "babb" | grep '^[^b]*bb[^b]*$' where the string should match but the 1st letter is b. You rule that out with ^[^b].
    – terdon
    Nov 23, 2014 at 12:56
2
grep '\(^\|[^b]\)bb\([^b]\|$\)'

or

grep -E '(^|[^b])bb([^b]|$)'

That is: search for an occurrence of bb that is preceded by either the beginning of the line or a character different from b, and that is followed by either a character different from b or the end of the line.

0

You must log in to answer this question.

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