![awk 中的条件语句](https://linux22.com/image/1193148/awk%20%E4%B8%AD%E7%9A%84%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5.png)
if
在 bash 中,我可以对语句执行快捷条件
(( globrl == 1 )) && var=val
awk 中是否存在等效的东西,而不必使用直接if
条件?
答案1
是的, ...
# If the second field is "3" print it
$ echo "2 3" | awk '{if ($2 == 3) print $2}'
3
# If the second field is "3" print it
$ echo "2 3" | awk '($2 == 3) {print $2}'
3
# If the second field is "3" print it
$ echo "2 3" | awk '$2==3{print $2}'
3
# If a match for "3" is in a line print the first field of this line
$ echo "2 3" | awk '/3/{print $1}'
2
# If the second field is "3" assign the value of "4" to the variable var then print it
$ echo "2 3" | awk '$2==3{var=4; print var}'
4
# If the second field is "3" assign the value of "yes" to the variable var or otherwise assign "no" to it and print it
$ echo "2 3" | awk 'var = $2 == 3 ? "yes" : "no" {print var}'
yes
# If the second field is "2" assign the value of "yes" to the variable var or otherwise assign "no" to it and print it
$ echo "2 3" | awk 'var=$2==2?"yes":"no"{print var}'
no
# Same as the above but utilizing the conditional expression with the ternary operator ‘?:’ in a function
$ echo "2 3" | awk 'function myfunc(field){var = field == 2 ? "yes" : "no"}; myfunc($2); {print var}'
no