Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 244
Ankur Agarwal Avatar asked Mar 03 '12 03:03

Ankur Agarwal


People also ask

How do you find a line that occurs only once Linux?

The uniq command reports or omits repeated lines and by passing it the -u argument we tell it to report only unique lines. Used together like this, the command will sort data. txt lexicographically by each line, find the unique line and print it back in the terminal for you.


2 Answers

Do you want grep to stop matching or do you only care about the first match. You could use head if the later is true...

`grep stuff | head -n 1` 

Grep is a line based util so the -m 1 flag tells grep to stop after it matches the first line which when combined with head is pretty good in practice.

like image 193
Andrew White Avatar answered Oct 07 '22 13:10

Andrew White


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!!

like image 5
MacUsers Avatar answered Oct 07 '22 14:10

MacUsers