Read a file by bytes in BASH

后端 未结 7 2020
囚心锁ツ
囚心锁ツ 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条回答
  •  Happy的楠姐
    2020-12-06 01:03

    Although I rather wanted to expand Perleone's own post (as it was his basic concept!), my edit was rejected after all, and I was kindly adviced that this should be posted as a separate answer. Fair enough, so I will do that.

    Considerations in short for the improvements on Perleone's original script:

    • seq would be totally overkill here. A simple while loop with a used as a (likewise simple) counter variable will do the job just fine (and much quicker too)
    • The max value, $(cat $1 | wc -c) must be assigned to a variable, otherwise it will be recalculated every time and make this alternate script run even slower than the one it was derived from.
    • There's no need to waste a function on a simple usage info line. However, it is necessary to know about the (mandatory) curly braces around two commands, for without the { }, the exit 1 command will be executed in either case, and the script interpreter will never make it to the loop. (Last note: ( ) will work too, but not in the same way! Parentheses will spawn a subshell, whilst curly braces will execute commands inside them in the current shell.)
    #!/bin/bash
    
    test -s "$1" || { echo "Need a file with size greater than 0!"; exit 1; }
    
    a=0
    max=$(cat $1 | wc -c)
    while [[ $((++a)) -lt $max ]]; do
      cat $1 | head -c$a | tail -c1 | \
      xargs -0 -I{} printf '%c %#02x\n' {} "'{}"
    done
    

提交回复
热议问题