Grep: how to use a non-capture group?

I got confused in the next team

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

I think it should be output as

1 
2 
3
1
2
3

But it prints like

1
2
3
1
2nd
3th  

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

+4
source share
1 answer

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
+3
source

All Articles