Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

Here's the command :

grep '\(2\)[[:digit:]]\{\1\}' numbers

What I want is to match exactly 2 digits after the digit '2', 3 digits if I change the digit '2' to '3' in my expression, 4 digits if ...

I'm using back-referencing here but when I execute this command I have the following output :

grep: invalid content of \{\}

How could one change my expression ?

first solution : As serge answered :

2[[:digit:]]\{1\}\|3[[:digit:]]\{2\}\|4[[:digit:]]\{3\}\|5[[:digit:]]\{4\}

That could actually work, but let's suppose I have \(34\) as the first sub-expression, I wish I could back-referencing that number so I don't have to implement the 34 cases (or more).

share|improve this question
    
i think it should be grep -E 'pattern' inputfile –  Rahul Patil Feb 26 '13 at 8:15
    
@RahulPatil what is wrong to use Basic Regular Expressions ? for readability reason I could have used that right. But that doesn't help a lot since '{\1}' doesn't give any result still. –  Oddant Feb 26 '13 at 8:39
    
there are only 10 digits including '0' –  Serge Feb 26 '13 at 8:59
1  
@Oddant : Serge is logically correct, either there are only 10 possible cases or there is some token between the first "digit"(s) and the rest, or you are assuming something else about the context but using grep wrongly in your description. –  goldilocks Feb 26 '13 at 9:13
    
@goldilocks please check my update –  Oddant Feb 26 '13 at 21:08

2 Answers 2

Back-references are not allowed here. You have to write the expression that will describe all possible cases, e.g.:

2[[:digit:]]\{1\}\|3[[:digit:]]\{2\}\|4[[:digit:]]\{3\}\|5[[:digit:]]\{4\}
share|improve this answer
    
that could actually work, but please check my update to read why it is not really appropriate. –  Oddant Feb 26 '13 at 8:48
    
For completeness, grep --line-regexp '1\|2[[:digit:]]\{1\}\|3[[:digit:]]\{2\}\|4[[:digit:]]\{3\}\|5[[:digit:]]\{4\}\|‌​6[[:digit:]]\{5\}\|7[[:digit:]]\{6\}\|8[[:digit:]]\{7\}\|9[[:digit:]]\{8\}' numbers –  l0b0 Feb 26 '13 at 12:20
    
@Serge pease check my update –  Oddant Feb 26 '13 at 21:09

It looks like you mean to hard-code the that first value instead of determining it from the actual first digit of the line. Consider something like this, then:

HOWMUCH=2 grep "\($HOWMUCH\)[[:digit:]]\{$HOWMUCH\}" numbers
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.