Reputation: 4597
Using AWK
, I need to avoid print lines with a specific word in a specific field...
Before someone call it's a duplicate, I did search, and found this: Match string not containg a certain phrase, but I think it's other context, because here I need match in a specific column.
Given the data:
ABC ABC
DEF AAA
GHI ABC
I want to filter to print full lines only with text not containing ABC in fist field(lines 2 and 3).
As a first try, I tried (?!...)
and expected to work this way to return DEF
and GHI
:
echo -e "ABC\tABC\nDEF\tAAA\nGHI\tABC" | awk '$1 ~ /(?!ABC)/ {print}'
but return nothing.
Second try... using not before the expression !/.../
:
~$ echo -e "ABC\tABC\nDEF\tAAA\nGHI\tABC" | awk '$1 ~ !/ABC/ {print}'
Return nothing too.
I don't understand why...
So another shot fails (as expected this time):
~$ echo -e "ABC\tABC\nDEF\tAAA\nGHI\tABC" | awk '!/ABC/ {print}'
DEF AAA
As expected this time, the second field was filtered too. So, it seems it work only to $0
.
Then I did my homework and got it working this way:
~$ echo -e "ABC\tABC\nDEF\tAAA\nGHI\tABC" | awk '{FL=$0;$0=$1}; !/ABC/ {print FL}; { $0=FL }'
DEF AAA
GHI ABC
Anyway, this looks a workaround for me, and I have a bad feeling that I'm not doing in the right way.
Someone know a better way, or at least explain why the first and second tries do not worked ?
Upvotes: 1
Views: 99
Reputation: 41460
This awk
should do:
awk '!/^ABC/' file
DEF AAA
GHI ABC
It will print lines not (!
) starting (^
) with ABC
Upvotes: 0
Reputation: 158100
You can use the following idiom:
awk '$1 !~ /ABC/' file
If the first field does not contain ABC
the line gets printed. (The matches not operator is !~
). Note that the command contains a condition only and no print
action. This can work since the default action in awk
is print
and therefore does not need to get specified explicitly.
Upvotes: 2