How to check if a file contains only zeros in a Linux shell?

后端 未结 6 2080
隐瞒了意图╮
隐瞒了意图╮ 2021-01-04 07:36

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 ov

6条回答
  •  耶瑟儿~
    2021-01-04 08:12

    It won't win a prize for elegance, but:

    xxd -p file | grep -qEv '^(00)*$'
    

    xxd -p prints a file in the following way:

    23696e636c756465203c6572726e6f2e683e0a23696e636c756465203c73
    7464696f2e683e0a23696e636c756465203c7374646c69622e683e0a2369
    6e636c756465203c737472696e672e683e0a0a766f696420757361676528
    63686172202a70726f676e616d65290a7b0a09667072696e746628737464
    6572722c202255736167653a202573203c
    

    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.

提交回复
热议问题