我在这样简单的测试中遇到两个变量的错误:
$ echo test|awk '{$2 != ""? o="ABC" r="123" : o="123 r="ABC"}END{print "o:"o" r:"r}'
awk: cmd. line:1: {$2 != ""? o="ABC" r="123" : o="123 r="ABC"}END{print "o:"o" r:"r}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {$2 != ""? o="ABC" r="123" : o="123 r="ABC"}END{print "o:"o" r:"r}
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {$2 != ""? o="ABC" r="123" : o="123 r="ABC"}END{print "o:"o" r:"r}
awk: cmd. line:1: ^ unterminated string
$
对于单个变量,它工作得很好:
$ echo test|awk '{$1 != ""? o="ABC" : o="123"}END{print "o:"o}'
o:ABC
$ echo test|awk '{$2 != ""? o="ABC" : o="123"}END{print "o:"o}'
o:123
答案1
您实际上无法使用? :
运算符来做到这一点,因为它只能处理单个值,并且两个赋值将生成两个值。
使用实际的if
语句来代替:
$ echo test|awk '{ if ($2 != "") { o="ABC"; r="123" } else { o="123"; r="ABC" }} END{ print "o:"o" r:"r}'
o:123 r:ABC