我是 awk
的新手,我想知道是否可以为 awk
上的 if
操作获得一个结果。
例子:
cat example.txt
:
0
0
0
0
0
awk '{ if ($1==0) print "all zeros"; else print "there is 1"}'
结果:
all zeros
all zeros
all zeros
all zeros
all zeros
我希望只有一个 all zeros
作为答案或 TRUE
。这是我应该使用 awk
函数返回一些东西的情况吗?谢谢
最佳答案
以这种方式保存您的代码。使用所示示例编写和测试。
awk '$0==0{count++} END{if(count==FNR){print "TRUE"}}' Input_file
或
awk '$0==0{count++} END{if(count==FNR){print "All lines are zeroes"}}' Input_file
或者在找到一些非零行时打印一条消息:
awk '$0==0{count++} END{if(count==FNR){print "TRUE"} else{print "There is non-zero line(s) found."}}' Input_file
说明:为上述添加详细说明。
awk ' ##Starting awk program from here.
$0==0{ ##Checking condition if current line is zero then do following.
count++ ##Increasing count with 1 here.
}
END{ ##Starting END block of this program from here.
if(count==FNR){ ##Checking condition if count is equal to number of total lines of file.
print "TRUE" ##If above condition is TRUE then print TRUE here.
}
}
' Input_file ##Mentioning Input_file name here.
关于awk 使用 if 语句在一个句子中获取多行的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67103573/