I need to match a pattern with grep, only if it starts at position 16. Let's 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 this regular expression

egrep '.*\{15\} pattern'

but this does not seem to work as desired.

Can somebody please suggest a solution?

  • 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 '14 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 '14 at 14:13

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'

This 'matches' the pattern part only.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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