Evaluate Expression within awk
I want to create a conditional expression string and pass in an awk script. My script is as below...
comm="\$3 == "hello""
awk -F "^T" -v command="${comm}" '
{ if ( command ) { print "hye" } if ( $3 == "hello" ) { print "bye" }
}' testBut the statement "if ( command )" always evaluates to true which is not correct. I want to know the correct way of executing this statement..
On Running...
./test_awk.shIt returns
hyeWhich is not the expected answer.
Test file has following ( just a sample ):
hello^Thye^TbyeMany thanks in advance
122 Answers
If the logical operation is always the same (i.e. in this case ==) and you just want to change the field number and the value against which it is tested, then you can pass them as separate variables e.g.
#!/bin/bash
awk -v field=3 -v value="hello" '
{ if ( $field == value ) { print "hye" } if ( $3 == "hello" ) { print "bye" }
}' testIf you truly want to create a variable awk script, then IMHO a different approach is required, for example using a here document to write the awk script on the fly using the shell to expand your command variable - something like
#!/bin/bash
mycommand="\$3 == \"hello\""
awk -f- test << EOF
{ if ( ${mycommand} ) { print "hye" } if ( \$3 == "hello" ) { print "bye" }
}
EOF 1 Lets trace:
$ cat test
hello^Thye^Tbye
$ awk '{ print ($3 == hello) ? "true" : "false" }' test
true # wrong output
$ awk '{ print ($3 == "hello") ? "true" : "false" }' test
false # correct outputaccording to trace when we use $3 == hello we get wrong output and when changed to $3 == "hello" including with double quote around the string the output is correct.
So we found the wrong statement and the problem is on comm variable value if you set:
$ comm="\$3 == "hello""and take echo:
$ echo $commyou will see the comm variable has below value in it
$3 == helloso you need double quote around the value then edit your value with this one:
$ comm="\$3 == \"hello\""
$ echo $comm
$3 == "hello"then go and improve your's. hope this helps.
2