6

How to skip N lines when a pattern is found in awk?

awk '{if ($0~/pattern/) skip N lines; else print $0}'

2 Answers 2

10

Let me show you how to make that awk solution more idiomatic (refer to the awk info page on stackoverflow).

Starting with:

$ seq 10 20 | awk '{if ($0 ~ /11/) {n=NR+6}; if (NR<n) next; print $0}'
10
17
18
19
20

First, we'll take the if statements, and turn them into condition {action} lines

awk '
    $0 ~ /11/ {n=NR+6}
    NR < n {next}
    {print $0}
'

Then, we'll use $0 as the default value for some things:

awk '
    /11/ {n=NR+6}
    NR < n {next}
    {print}
'

Then, we'll take {print} as the default action if the condition is true

awk '
    /11/ {n=NR+6}
    NR < n {next}
    1
'

Then, we'll invert the NR < n condition to remove the next

awk '
    /11/ {n=NR+6}
    NR >= n
'

And we can one-liner-ize it:

awk '/11/ {n=NR+6} NR >= n'

This produces the same output

$ seq 10 20 | awk '/11/ {n=NR+6} NR >= n'
10
17
18
19
20

Comparing:

awk '{if ($0 ~ /11/) {n=NR+6}; if (NR<n) next; print $0}'
awk '/11/ {n=NR+6} NR >= n'

As a last step, you might want to pass the pattern and the value of N as parameters into awk, so they don't have to be hardcoded. This inflates the awk call but might be more flexible for you:

awk -v patt="11" -v N=6 '$0 ~ patt {n = NR + N} NR >= n'

By placing the parameters after the awk script, -v can be dropped, making the command a bit shorter:

awk '$0 ~ patt {n = NR + N} NR >= n' patt=11 N=6

One advantage to putting the variables after the awk body is they can get different values for each file:

awk '$0 ~ patt {n = NR + N} NR >= n' patt=11 N=6 file1 N=10 file2
1
  • 2
    FWIW, here is the GNU sed equivalent to your one-liner-ized awk command: sed '/11/,+5 d' (lines matching pattern /11/ and the 5 next lines are deleted from the output)
    – xhienne
    Feb 2, 2021 at 10:58
2

N = number of lines to skip

awk '{if ($0~/pattern/) {n=NR+N;} if (NR<n) next; print $0;}'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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