简体   繁体   中英

How to grep with alternation

I would like to grep lines which include a comma followed by four identical digits followed by a comma followed by an alphabetic character.

I tried

grep -E ,'1111|2222|3333|4444|5555|6666|7777|8888|9999',[[:alpha:]] file

This doesn't seem to do what I describe. The problem is that it doesn't handle the commas and [[:alpha:]] properly it seems.

How can you do this?

It's because your alternation is not applied in the way you are expecting. To make it behave as you want, you need to use groups:

grep -E ,'(1111)|(2222)|(3333)|(4444)|(5555)|(6666)|(7777)|(8888)|(9999)',[[:alpha:]] file

Alternatively, this could be expressed more succinctly using a backref:

grep -E ,'([[:digit:]])\1{3},[[:alpha:]]' file

which basically means the same digit 4 times. This also includes 0, however, so it may or may not help you.

EDIT:

Of course... to make it only 1-9, you could

grep -E ,'([1-9])\1{3},[[:alpha:]]' file

为您尝试此正则表达式

',(1111|2222|3333|4444|5555|6666|7777|8888|9999|0000),\w'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM