Search code examples
perlunixawksedsolaris

need to convert the binary values to numbers


I have a file with below data

cat test.txt
010001010000010100000000000000000000000000000000000000000000000000000000000000000000000000000000000

two fields in above line represents usage one digit starting from 16

I want the the o/p in such that if 01 then it should print the digit, else put , and check next field.

first two fields 01 means 16 is used so it should be printed in o/p file 2nd two field 00 mean 17 is not used, so it should not be printed in o/p file ans so on.

Like wise there are 4000 fields, means 2000 digits starting from 16-2016

For above line , need output like

16,18,19,22,23,

Here's what I have so far.

cat counter_mfd.txt | cut -d\' -f2 | sed 's/.\{2\}/& /g' | awk -F, '{a[$2]=$1;} END{for(i in a)print i" "a[i];}'

awk: record `00 00 00 00 00 00 00...' too long


Solution

  • This should work as Perl is pretty normal on Solaris:

    perl -e '$s=16; foreach (<>=~m/.{2}/g){if($_=="01"){print "$s,"};$s++}' < test.txt 
    

    Output

    16,18,19,22,23,
    

    Explanation

    $s is just the starting value.

    foreach (<>=~m/.{2}/g) splits stdin into groups of two characters and then iterates over them setting $_ to each one in turn.

    The if checks if 2-digit string is "01" and prints $s if it is.

    Then $s is incremented whether the value was printed or not.