Reputation: 2923
I cant seem to figure out how to negate my condition with awk.
For example, lets say I have
g ha
a bb
g hc
f cd
t de
g pf
I can print just the ones with g and starts with h for the first and second column with:
cat test.txt | awk '$1 ~ /g/ && $2 ~ /^h/'
but how do I do the opposite, where I just want to print the ones that are not g
and start with h
. Basically to have the output:
a bb
f cd
t de
g pf
Upvotes: 0
Views: 207
Reputation: 203995
The negation (opposite) of $1 ~ /g/ && $2 ~ /^h/
or any other condition is simply sticking !
at the front of it:
$ awk '!($1 ~ /g/ && $2 ~ /^h/)' file
a bb
f cd
t de
g pf
but you can also apply boolean algebra to that (!(a && b)
= !a || !b
) to get:
$ awk '$1 !~ /g/ || $2 !~ /^h/' file
a bb
f cd
t de
g pf
Upvotes: 0
Reputation: 163457
You could also negate the whole match using !
As the first field is always a single character you can check if it is g
without using a regex notation because $1 ~ /g/
will still match if there is a g
somewhere in the string.
awk '!($1 == "g" && $2 ~ /^h/)' test.txt
Output
a bb
f cd
t de
g pf
Upvotes: 0
Reputation: 88766
If $1 ~ /g/ && $2 ~ /h/
is true then continue with the next line otherwise output the current line.
awk '$1 ~ /g/ && $2 ~ /h/{next} {print}' test.txt
Output:
a b f c t d g p
Upvotes: 2