Read a file by bytes in BASH

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

    using read a single char can be read at a time as follows:

    read -n 1 c
    echo $c   
    

    [ANSWER]

    Try this:

    #!/bin/bash
    # data file
    INPUT=/path/to/input.txt
    
    # while loop
    while IFS= read -r -n1 char
    do
            # display one character at a time
        echo  "$char"
    done < "$INPUT"
    

    From this link


    Second method, Using awk, loop through char by char

    awk '{for(i=1;i<=length;i++) print substr($0, i, 1)}' /home/cscape/Desktop/table2.sql


    third way,

    $ fold -1 /home/cscape/Desktop/table.sql  | awk '{print $0}'
    

    EDIT: To print each char as HEX number:

    Suppose I have a file name file :

    $ cat file
    123A3445F 
    

    I have written a awk script (named x.awk) to that read char by char from file and print into HEX :

    $ cat x.awk
    #!/bin/awk -f
    
    BEGIN    { _ord_init() }
    
    function _ord_init(    low, high, i, t)
    {
        low = sprintf("%c", 7) # BEL is ascii 7
        if (low == "\a") {    # regular ascii
            low = 0
            high = 127
        } else if (sprintf("%c", 128 + 7) == "\a") {
            # ascii, mark parity
            low = 128
            high = 255
        } else {        # ebcdic(!)
            low = 0
            high = 255
        }
    
        for (i = low; i <= high; i++) {
            t = sprintf("%c", i)
            _ord_[t] = i
        }
    }
    function ord(str,    c)
    {
        # only first character is of interest
        c = substr(str, 1, 1)
        return _ord_[c]
    }
    
    function chr(c)
    {
        # force c to be numeric by adding 0
        return sprintf("%c", c + 0)
    }
    
    { x=$0; printf("%s , %x\n",$0, ord(x) )} 
    

    To write this script I used awk-documentation
    Now, You can use this awk script for your work as follows:

    $ fold -1 /home/cscape/Desktop/file  | awk -f x.awk
    1 , 31
    2 , 32
    3 , 33
    A , 41
    3 , 33
    4 , 34
    4 , 34
    5 , 35
    F , 46
    

    NOTE: A value is 41 in HEX decimal. To print in decimal change %x to %d in last line of script x.awk.

    Give it a Try!!

提交回复
热议问题