awk-如果为空,则使用默认值打印最后一列的值

问题描述:

我正在使用awk命令来打印值.对于最后一列,如果未找到任何值,则需要它打印NA.

I am using awk command to print the values. For the last column, if no value is found, I need it to print NA.

例如,在下面的代码中,当$3NULL时,我需要打印为NA.

Ex., in the below code, when $3 is NULL, I need to print as NA.

无论如何,我可以包含if/isnull条件或其他内容.

Is there anyway I could include a if/isnull condition or something.

awk -F"    " '{ print $1,"|", $2, "|", $3 }' log_temp.txt > log_template.txt

无论如何,我是否可以包含'if'/'isnull'条件或其他内容.

Is there anyway i could include a 'if'/'isnull' condition or something.

您需要使用 三元运算符

You need to use ternary operator

语法:

Syntax:

condition ? value_if_true : value_if_false

对于第三列

awk '{ print ($3==""?"NA":$3) }' infile

因此成为

awk '{ print $1, "|" , $2, "|",  ($3==""?"NA":$3) }' infile

您还可以设置输出字段分隔符变量(OFS)

You can also set output field separator variable (OFS)

awk -v OFS='|' '{ print $1, $2, ($3=="" ? "NA" : $3) }' infile

print ($3=="" ? "NA" : $3)

if( $3=="" ){
    print "NA"
}else{
    print $3
}  

对于最后一列,您可以使用NF变量,该变量不提供 记录,而$NF是最后一列

For last column you can use NF variable which gives no of fields in record, whereas $NF is last column