How to check if a large file contains only zero bytes ('\0'
) in Linux using a shell command? I can write a small program for this but this seems to be an overkill.
相关问题
- How to get the return code of a shell script in lu
- Is shmid returned by shmget() unique across proces
- What is the best way to do a search in a large fil
- how to get running process information in java?
- Spring Integration - Inbound file endpoint. How to
If you have Bash,
If you don't have Bash, the following should be POSIX (but I guess there may be legacy versions of
cmp
which are not comfortable with reading standard input):Perhaps more economically, assuming your
grep
can read arbitrary binary data,I suppose you could tweak the last example even further with a
dd
pipe to truncate any output fromtr
after one block of data (in case there are very long sequences without newlines), or even down to one byte. Or maybe just force there to be newlines.The "file"
/dev/zero
returns a sequence of zero bytes on read, so acmp file /dev/zero
should give essentially what you want (reporting the first different byte just beyond the length offile
).It won't win a prize for elegance, but:
xxd -p
prints a file in the following way:So we grep to see if there is a line that is not made completely out of 0's, which means there is a char different to '\0' in the file. If not, the file is made completely out of zero-chars.
(The return code signals which one happened, I assumed you wanted it for a script. If not, tell me and I'll write something else)
EDIT: added -E for grouping and -q to discard output.
Straightforward:
The
tr -d
removes all null bytes. If there are any left, theif [ -n
sees a nonempty string.If you're using bash, you can use
read -n 1
to exit early if a non-NUL
character has been found:where you substitute the actual filename for
your_file
.Completely changed my answer based on the reply here
Try