简体   繁体   English

如何在bash脚本中使用awk检查文件是否为空?

[英]How to check if a file is empty using awk in a bash script?

I am trying to check if a file is empty using awk in a bash script. 我试图在bash脚本中使用awk检查文件是否为空。 This condition for a file being empty is the following: If a file only has its first row with field values followed by ------ (and followed by nothing else) then it is considered empty. 文件为空的此条件如下:如果文件的第一行的字段值后跟------ (后面没有其他内容),则认为该文件为空。

Here is the structure of that special file: 这是特殊文件的结构:

file.txt file.txt的

col1   col2   col3   col4   col5
------

So far this is what I have: 到目前为止,这就是我所拥有的:

awk '
    {
      if (NR > 2)
        print "NOT EMPTY"
      else
        print "EMPTY"
    }
' file.txt

The output I want is: 我想要的输出是:

EMPTY

The empty I am getting is: 我得到的空虚是:

EMPTY
EMPTY

How do I get only EMPTY as one output? 如何仅将EMPTY作为一个输出? I know it might be very simple but I couldn't find anything. 我知道这可能很简单但我找不到任何东西。 Thanks! 谢谢!

Let me know if further explanation is needed. 如果需要进一步解释,请告诉我。

EDIT: Also, if extra blank lines are added to file.txt, then it will print EMPTY for as many extra line there is. 编辑:此外,如果额外的空行添加到file.txt,那么它将打印EMPTY为多少额外的行。 Is there a more general approach to this? 有更一般的方法吗?

awk 'END{print(NR>2)?"NOT EMPTY":"EMPTY"}'

You need to put your awk logic in END block otherwise it is executed for each line of input: 您需要将awk逻辑放在END块中,否则将为每行输入执行:

awk '
    END {
      if (NR > 2)
        print "NOT EMPTY"
      else
        print "EMPTY"
    }
' file.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM