Search code examples
perlbinarydecode

Decode binary octet string in a file with perl


I have a file that contains for some of the lines a number that is coded as text -> binary -> octets and I need to decode that to end up with the number. All the lines where this encoded string is, begins with STRVID:

For example I have in one of the lines:

STRVID: SarI3gXp

If I do this echo "SarI3gXp" | perl -lpe '$_=unpack"B*"' I get the number in binary

0101001101100001011100100100100100110011011001110101100001110000

Now just to decode from binary to octets I do this (assign the previous command to a variable and then convert binary to octets

variable=$(echo "SarI3gXp" | perl -lpe '$_=unpack"B*"') ; printf '%x\n' "$((2#$variable))"

The result is the number but not in the correct order

5361724933675870

To get the previous number in the correct order I have to get for each couple of digits first the second digit and then the first digit to finally have the number I'm looking for. Something like this:

variable=$(echo "SarI3gXp" | perl -lpe '$_=unpack"B*"') ; printf '%x\n' "$((2#$variable))" | gawk 'BEGIN {FS = ""} {print $2 $1 $4 $3 $6 $5 $8 $7 $10 $9 $12 $11 $14 $13 $16 $15}'

And finally I have the number I'm looking for:

3516279433768507

I don't have any clue on how to do this automatically for every line that begins with STRVID: in my file. At the end what I need is the whole file but when a line begins with STRVID: then the decoded value.

When I find this:

STRVID: SarI3gXp

I will have in my file

STRVID: 3516279433768507

Can someone help with this?


Solution

  • First of all, all you need for the conversion is

    unpack "h*", "SarI3gXp"
    

    A perl one-liner using -p will execute the provided program for each line, and s///e allows us to modify a string with code as the replacement expression.

    perl -pe's/^STRVID:\s*\K\S+/ unpack "h*", $& /e'
    

    See Specifying file to process to Perl one-liner.