awk 使用 if 语句在一个句子中获取多行的结果

标签 awk

我是 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/

相关文章:

linux - 在文件末尾添加一列,其中包含特定行数的值

linux - 使用 sed 查找和替换带有 2 个分隔符的字符的好方法

AWK - 如果在 Test1 的行中找到 Test2 中的列,则在 Test1 中插入 1 else 0

linux - Bash:比较两个文件并更改输出

linux - 如何在 awk 中回显变量以创建新文件

linux - AWK 函数的问题

unix - awk 不能重新创建它删除的文件?

linux - 忽略 find 命令中的目录

shell - "grep"从一行的最后 24 个字符中的前 12 个字符

database - 如何使用 sed 使用引用文件在文件中进行数千次替换?