Identify empty file with null record

Hi Team,

I have a file abc.dat which is a empty file. But it has null record in first line. I need to identify this unique file and handle it separately.

scenario 1:

abc/dw> wc abc.dat
1 0 1 abc.dat
abc/dw> cat abc.dat

abc/dw>

scenario 2:

abc/dw> wc pqr.dat
0 0 0 pqr.dat
abc/dw> cat pqr.dat

abc/dw>

scenario 3:

abc/dw> wc xyz.dat
2 2 2 xyz.dat
abc/dw> cat xyz.dat
adf 
adsf
abc/dw>

If the file has null record in it
then echo "empty file with null record" -- abc.dat
else echo "empty file" -- pqr.dat
else echo "file has data in it" -- xyz.dat

Can anyone help me out?

The following script assumes that /bin/sh is a Posix-compatible shell.
If the raw read is successful then it has got a record, then the record is tested for being zero (empty, null).

#!/bin/sh
if IFS= read -r line < "$1"
then
  if [ -z "$line" ]
  then
    echo "file with null record"
  else
    echo "file has data in it"
  fi
else
  echo "empty file"
fi

The script takes a file name as argument, otherwise reads from stdin.
For academic interest, the following works identically because the if ... fi is a block where input and output can be redirected.
The difference is, that the input file is open throughout the block, so another read in the block would read the next line.

#!/bin/sh
if IFS= read -r line
then
  if [ -z "$line" ]
  then
    echo "file with null record"
  else
    echo "file has data in it"
  fi
else
  echo "empty file"
fi < "$1"

How about

case "$(wc -c <file)" in 0) echo empty file;; 1) echo file with null record;;  *) echo file with data;; esac

It would work on the given examples, but fail if a (non-*nix-text) file with a single character but without line terminator were encountered.

1 Like

wc has two problems.

  1. wc goes through the entire file. Can take a long time.
  2. works only with GNU wc. A Unix wc puts leading spaces (BTW a frequent obstacle); the case does not match.
1 Like