Read a file by bytes in BASH

后端 未结 7 2012
囚心锁ツ
囚心锁ツ 2020-12-06 00:19

I need to read first byte of file I specified, then second byte,third and so on. How could I do it on BASH? P.S I need to get HEX of this bytes

7条回答
  •  情深已故
    2020-12-06 01:22

    Yet another solution, using head, tail and printf:

    for a in $( seq $( cat file.txt | wc -c ) ) ; do cat file.txt | head -c$a | tail -c1 | xargs -0 -I{} printf '%s %0X\n' {} "'{}" ; done
    

    More readable:

    #!/bin/bash
    
    function usage() {
        echo "Need file with size > 0"
        exit 1
    }
    
    test -s "$1" || usage
    
    for a in $( seq $( cat $1 | wc -c ) )
    do
        cat $1 | head -c$a | tail -c1 | \
        xargs -0 -I{} printf '%c %#02x\n' {} "'{}"
    done
    

提交回复
热议问题