1

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?

SLePort
  • 15,211
  • 3
  • 34
  • 44
Mike Dannyboy
  • 462
  • 1
  • 4
  • 13

2 Answers2

2

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
anubhava
  • 761,203
  • 64
  • 569
  • 643
0

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

awk -vf=awk '$0 ~ f && !/not/' file
grail
  • 914
  • 6
  • 14
  • There is nothing Gawk-specific here. This appears to be a tweaked-down restatement of Anubhava's existing answer. – tripleee Mar 16 '17 at 06:37