Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

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? 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. Is there a more general approach to this?

like image 644
Redson Avatar asked Oct 17 '25 08:10

Redson


2 Answers

You need to put your awk logic in END block otherwise it is executed for each line of input:

awk '
    END {
      if (NR > 2)
        print "NOT EMPTY"
      else
        print "EMPTY"
    }
' file.txt
like image 98
anubhava Avatar answered Oct 19 '25 22:10

anubhava


awk 'END{print(NR>2)?"NOT EMPTY":"EMPTY"}'
like image 32
Ell Avatar answered Oct 19 '25 22:10

Ell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!