Sunday, April 28, 2024
10
rated 0 times [  10] [ 0]  / answers: 1 / hits: 3795  / 2 Years ago, thu, april 28, 2022, 9:29:41

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


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

More From » command-line

 Answers
2

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

[#1997] Friday, April 29, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhaeams

Total Points: 115
Total Questions: 111
Total Answers: 103

Location: Burundi
Member since Wed, Nov 25, 2020
3 Years ago
;