0

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 ?

0

2 Answers 2

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
3
  • it does not work as expected. When I use bar as pattern, it matches any of the characters a, b, r: grep -P "(?<=.{19})[bar]+" Jan 26, 2021 at 6:18
  • @400theCat You have to adjust the regex according to the pattern you need. My answer reflected what you gave as example. For "bar" matching: grep -P "(?<=.{19})bar". Jan 26, 2021 at 6:55
  • @400theCat maybe I didn't need the [2]+, updated the answer. Jan 26, 2021 at 6:57
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.

2
  • that works. The only problem is that grep now color highlights the whole line up to my matching pattern, not just the pattern itself. Jan 26, 2021 at 5:37
  • Or grep '^.\{19\}.*2' or grep -E '^.{19}.*2'.
    – Quasímodo
    Jan 26, 2021 at 11:41

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.