1

Looking for command line tool (awk, sed, etc.) command to omit lines from the beginning of a file to the nth occurrence of a pattern. Stated another way, print only from the nth occurrence of pattern to end of file. Assume one match per line; line does not necessarily begin with pattern.

e.g. omit from beginning of file to second foo in the following:

something
abc foo1
maybe something else
foo2 -this line and anything before is gone- 
maybe not
foo3
something

Desired result:

maybe not
foo3
something

Bonus points for including/excluding the line with the nth occurrence.

4

To exclude the nth occurrence of the pattern

awk -v 'n=3' 'NR == 1, /pattern/ && !--n {next}; 1'

(replace 3 with the number of occurrences you want (2 in your case), and pattern with your actual pattern (foo in your case)).

Example:

$ seq 30 | awk -v 'n=3' 'NR == 1, /6/ && !--n {next}; 1'
27
28
29
30

To include the nth occurrence of the pattern

awk -v 'n=3' '/pattern/ && !--n, 0'

Example:

$ seq 30 | awk -v 'n=3' '/6/ && !--n, 0'
26
27
28
29
30
0
% perl -ne 'BEGIN{$NTH=2;$p=0} print if $p; /foo/ && $NTH--; $p=1 if !$NTH' input
maybe not
foo3
something

Where NTH is how many times, and then you need a to-print flag; decrement NTH on match and enable printing if NTH decremented enough. Move print to end to catch the ultimate desired foo.

  • I'm not familiar with perl. Couldn't make it capture the second foo. Can you give the command for that? – JB0x2D1 Nov 4 '16 at 14:06

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.