5

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.

1
  • 4
    A non-capturing group doesn't prevent any substring to be in the whole match result. It only avoids to create a capture (a separate substring accessible with the group number). Commented Jul 9, 2015 at 10:22

1 Answer 1

4

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 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.