Read a file by bytes in BASH

后端 未结 7 2034
囚心锁ツ
囚心锁ツ 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:04

    I have a suggestion to give, but would like a feedback from everybody and manly a personal advice from syntaxerror's user.

    I don't know much about bash but I thought maybe it would be better to have "cat $1" stored in a variable.. but the problem is that echo command will also bring a small overhead right?

    test -s "$1" || (echo "Need a file with size greater than 0!"; exit 1)
    a=0
    rfile=$(cat $1)
    max=$(echo $rfile | wc -c)
    while [[ $((++a)) -lt $max ]]; do
      echo $rfile | head -c$a | tail -c1 | \
      xargs -0 -I{} printf '%c %#02x\n' {} "'{}"
    done
    

    in my opinion it would have a better performance but i haven't perf'tested..

提交回复
热议问题