Yu Fu
Yu Fu

Reputation: 1201

Confusion about conditional expression in AWK

Here is my input file:

$ cat abc
0   1
2   3
4   5

Why does the following give a one-column output instead of a two-column one?

$ cat abc | awk '{ print $1==0?"000":"111" $1==0? "222":"333" }'
000
333
333

Shouldn't the output be the following?

000 222
111 333
111 333

Upvotes: 0

Views: 144

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753455

I think awk is going to parse this as:

awk '{ print ($1==0) ? "000" : (("111" $1==0) ? "222" : "333") }'

That is, when it prints the three zeros, it doesn't even consider the rest of the operation. And when it doesn't print the three zeros, it prints the triple threes because "111" concatenated with any string is not going to evaluate to zero.

You probably want to use:

awk '{ print ($1==0?"000":"111"), ($1==0? "222":"333") }'

where the comma puts a space (OFS or output field separator, to be precise) in the output between the two strings. Or you might prefer:

awk '{ print ($1==0?"000":"111") ($1==0? "222":"333") }'

which concatenates the two strings with no space.

Upvotes: 1

Related Questions