-1

I have file containing lines in following format:

2021-Jan-26 05:35  foo bar 2
2021-Jan-26 05:37  asdf 2 foo bar
2021-Jan-26 05:37  foo

The patterns that I am interested start at position 20. So when I grep the file for specific pattern, I want to skip (not match) first 19 characters.

So, I want to match a pattern anywhere on the line, except first 19 characters

In the example above, if I grep for 2, I only want to match lines 1 and 2.

How can I do this with grep ?

Martin Vegter
  • 358
  • 75
  • 236
  • 411

2 Answers2

2

You actually do want to match the first 19, but match them to "anything".

So

grep '^....................*2' 

There are 20 dots. The ^ anchors the pattern to the start of the line. The next 19 dots match one character each, in effect skipping over them. Then come .* which matches zero or more character, then comes 2 to match the pattern you want.

You can make this potentially more efficient with

grep '^..................[^2]*2'

which matches start of line, then 19 characters, then zero or more characters which are not 2 then a 2. There will not be any significant difference in this case but if the pattern being searched for is more elaborate then this optimization may help a lot.

icarus
  • 17,920
2

An option using GNU grep, that will ignore the first 19 characters and match only the pattern you need:

grep -P "(?<=.{19})2" file

Output:

2021-Jan-26 05:35  foo bar 2
2021-Jan-26 05:37  asdf 2 foo bar