awk if find pattern skip n lines

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

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

2 Answers

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

N = number of lines to skip

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like