What is wrong with below command
awk 'BEGIN {a = 5;b=6; (a==b)? print "a==b" : print "a!=b"}'
Output :
awk: BEGIN {a = 5;b=6; (a==b)? print "a==b" : print "a!=b"}
awk: ^ syntax error
Like many other programming languages, awk distinguishes between expressions and statements. By and large, statements are actions that are carried out, while expressions are computations that result in a value.
The ternary operator in awk, like its counterpart in C where it comes from, is itself an expression (not a statement) that expects three other expressions as expr1 ? expr2 : expr3. print is a statement. It cannot be used where an expression is called for, hence the syntax error.
Have you tried awk 'BEGIN {a = 5;b=6; print (a==b)? "a==b" : "a!=b"}' ?
Using a statement where an expression is called for cannot make any sense. Statements don't return values. So when you have condition ? stmt1 : stmt2, what is the value computed by the ternary operator? If condition is false, it should be the value of stmt2 but that's not a value, it's an action.
x = if true; print "yes"; else; print "no"; end
(cond1) ? printf("str1") : printf("str2")? Thanks explaining the subtleties of the ternary. EDIT: in fact, using the following ugly construction: str = (cond1) ? sprintf("str1") : sprintf("str2"); printf("%s", str) works, but at this point its almost as compact and much more clear to use if/else :)