Ren
Ren

Reputation: 2946

grep:how to use non-capturing group?

I am confused about the following command

$ cat num.txt  
1
2
3
1st
2nd
3th
$ cat num.txt | grep -Eo '[0-9](?:st|nd|th)?'  

I think it should output as

1 
2 
3
1
2
3

But it output as

1
2
3
1
2nd
3th  

What am I doing wrong here?Thanks for any help.

Upvotes: 5

Views: 3826

Answers (1)

anubhava
anubhava

Reputation: 784958

You can use:

grep -Eo '^[0-9]+' file
1
2
3
1
2
3

Or using lookahead in grep -P:

grep -Po '[0-9]+(?=st|nd|th)?' file
1
2
3
1
2
3

Upvotes: 4

Related Questions