Search code examples
regexlinuxbashgrep

Use grep to match a pattern in a line only once


I have this:

echo 12345 | grep -o '[[:digit:]]\{1,4\}'

Which gives this:

1234
5

I understand whats happening. How do I stop grep from trying to continue matching after 1 successful match?

How do I get only

1234

Solution

  • You need to do the grouping: \(...\) followed by the exact number of occurrence: \{<n>\} to do the job:

    maci:~ san$ echo 12345 | grep -o '\([[:digit:]]\)\{4\}'
    1234
    

    Hope it helps. Cheers!!