Vignesh I
Vignesh I

Reputation: 2221

A way to get around next in awk

I have to print the next line if the previous line matches a condition.

file a.dat with below contents

1
2
3
1
2
1

if $1 matches 3 then print 1(next line). I tried it with below awk statement

awk ' { if($1=="3") { {next} {print $1} } }' a.dat

but it didn't work. When i was looking for it i understood that when awk encounters a next no further rules are executed for the current record, hence i got an empty result. Is there a way to get around this with next itself using awk.

Upvotes: 0

Views: 251

Answers (3)

Jotne
Jotne

Reputation: 41456

This will print the next line if pattern is true:

awk '_-->0;$1==3{_=1}' file
4

some more readable..

awk 'f-->0;$1==3{f=1}' file

or as Ed suggested.

awk 'f&&f--;$1==3{f=1}' file

Another variation

awk '/^3$/{f=1;next} f-->0' file

Upvotes: 0

Arjun Mathew Dan
Arjun Mathew Dan

Reputation: 5298

awk '/bbbbb/{a=1;next}a{print;a=0}' File

Pattern being searched for is bbbbb. If pattern found, set variable a to 1. Goto next record. If a is 1, print the record and unset a. This will print the next line for all the lines matching the pattern.

Sample:

AMD$ cat File
aaaaa
bbbbb
ccccc
ddddd
eeeee
aaaaa
bbbbb
ccccc
ddddd
eeeee
AMD$ awk '/bbbbb/{a=1;next}a{print;a=0}' File
ccccc
ccccc

Upvotes: 2

Ed Morton
Ed Morton

Reputation: 203324

It's not clear when you say "matches 3" if you mean contains 3 or is numerically equal to 3 or is string equal to 3 or something else or if you want to print every line that follows a 3 or just the first or if you want to print a line containing 3 if the previous line was 3 or skip until you reach a non-3 but the general approach would be based on:

awk 'f{print; f=0} $0==3{f=1}' file

or even:

awk 'f&&f--; $0==3{f=1}' file

The variable f is commonly used to mean found. See https://stackoverflow.com/a/17914105/1745001 for how to generally print lines after matches with awk.

Upvotes: 2

Related Questions