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.

I need to match a pattern with grep, only if it starts at position 16. Lets suppose I want to match the string ' pattern' (starting with space)

the following should match

bla bla bla bla pattern

whereas following should not match, because the search pattern does not start at pos. 16:

bla bla bla bla foo foo pattern

I have tried using regular expression

egrep '.*\{15\} pattern'

but this does not seem to work as desired.

Can somebody please suggest a solution?

share|improve this question
1  
What do you mean by position? Does a TAB character count as one position. What about multi-byte characters? –  Stéphane Chazelas Apr 2 at 13:57
1  
You do not need to escape the metacharacters ( ) and { } in extended regular expressions. You are using egrep so by escaping those you are matching literal { and }. Don't escape those and your regex would work. –  devnull Apr 2 at 14:13

1 Answer 1

up vote 2 down vote accepted

I think what you are looking for is:

grep -E '^.{15} pattern'

This will be fine in most usage cases. However note that it won't 'match' just the pattern part, but everything before it will be included in the match too. You will see this by the highlighting of grep (if --color is given directly or has been included in a shell alias). Without colour, it will affect grep -o which prints just the matched part. Eg:

$ echo 'bla bla bla bla pattern' | grep -Eo '^.{15}( pattern)'
bla bla bla bla pattern

To avoid this with GNU grep, you can use a perl expression with look behind. Eg:

$ echo 'bla bla bla bla pattern' | grep -Po '(?<=^.{15}) pattern'
 pattern

This 'matches' the pattern part only.

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.