Homap
Homap

Reputation: 2214

awk printing against the condition

I have a simple question but I could not figure it out.

I have a file that I want to print all the lines that DO NOT match the condition I specify in the awk if condition. But I can just get to print the condition, how the other would work?

This is my code:

awk '{if ($18==0 && $19==0 && $20==0 && $21==0) print $0}' file

I also tried this:

awk '{if !($18==0 && $19==0 && $20==0 && $21==0) print $0}' file

But the second one doesn't work, any help is appreciated. Thank you.

Upvotes: 1

Views: 655

Answers (3)

jrjc
jrjc

Reputation: 21873

You could also reverse your conditional statement:

you want the opposite of :

awk '{if ($18==0 && $19==0 && $20==0 && $21==0) print $0}' file

Which can either be :

awk '{if ($18!=0 || $19!=0 || $20!=0 || $21!=0) print $0}' file

or

awk '{if (!($18==0 && $19==0 && $20==0 && $21==0)) print $0}' file

Example :

!cat file
A 0 0 0
B 1 1 1
C 1 0 1

awk '$2+$3+$4!=0' file
B 1 1 1
C 1 0 1

awk '{if ($2!=0 || $3!=0 || $4!=0) print $0}' file
B 1 1 1
C 1 0 1

awk '{if (!($2==0 && $3==0 && $4==0)) print $0}' file
B 1 1 1
C 1 0 1

awk '{if (!($2==0 || $3==0 || $4==0)) print $0}' file
B 1 1 1

Upvotes: 0

Jotne
Jotne

Reputation: 41446

Here you can do:

awk '$18+$19+$20+$21!=0' file

print $0 is not needed, since its default action.

Upvotes: 6

heptadecagram
heptadecagram

Reputation: 898

The negation (!) needs to be inside the parentheses:

awk '{if (!($18==0 && $19==0 && $20==0 && $21==0)) print $0}' file

And we add another set inside to wrap everything.

(FYI, if you had given how it "didn't work" (i.e., a syntax error on !, that would have been more helpful. Please remember to include error messages or symptoms of something not working for future questions!)

Upvotes: 2

Related Questions