Mike Dannyboy
Mike Dannyboy

Reputation: 483

Awk multiple search terms with a variable and negation

I have a little test file containing:

awk this   
and not awk this  
but awk this  
so do awk this  

And I've tried the following awk commands, in bash, but each produces no output:

f=awk; awk '/$f/ && !/not/' test.txt
f=awk; awk '/\$f/ && !/not/' test.txt
f=awk; awk '/"$f"/ && !/not/' test.txt
f=awk; awk -v f="$f" '/f/ && !/not/' gtest.txt

Using double quotes " produces "event not found" error in the shell due to the !.

How can I search on a variable and negate another string in the same command?

Upvotes: 1

Views: 323

Answers (2)

grail
grail

Reputation: 930

awk points to gawk for me and the following worked just fine:

awk -vf=awk '$0 ~ f && !/not/' file

Upvotes: 0

anubhava
anubhava

Reputation: 785541

Use awk like this:

f='awk'

awk -v f="$f" -v n='not' '$0 ~ f && $0 !~ n' file
awk this
but awk this
so do awk this

Or if you don't want to pass n='not' to awk:

awk -v f="$f" '$0 ~ f && $0 !~ /not/' file

awk this
but awk this
so do awk this

Upvotes: 2

Related Questions