1

I want to do some manipulation on a file with values coded by ASCII symbols.

I have a test file that looks something like this:

a>
b!

I would like to use an awk script to to convert them to integer values and then do further manipulation. I've looked and found a method of converting ASCII to integer:

for(n=0;n<256;n++)chr[n]=sprintf("%c",n)

but I don't know how to pass my integer values from this array to another array wherein I want to do my numeric manipulation.

Example output would be:

195
95

I can get it to work if I use a test file like this (without incorporation of the above code):

11
22

and the code:

cat testfile.txt | awk 'BEGIN {FS=""} {for (i=1;i<=NF;i++) ar[i]=ar[i]+$i} 
END {for(y=1;y<=length(ar);y++) print ar[y]}'

I get the desired result:

3
3

Does anyone have suggestions for how to convert the ASCII into an integer and then pass it to the rest of my awk statement?

reedms
  • 155
  • 1
  • 12
  • You want to translate character a to Value 97 and the '>' to value 62? Thats ugly in awk. Your for-loop generates an lookup for the invers problem. Would it be possible to do an 'od -t x1 inputfile' and then process the result with awk? – tue Mar 11 '14 at 08:34
  • I cannot understand why you got `10.5 and 47.5` where did the `.5` come from? can you give an example input with both cases (char and number etc), and also attached with an output file, better with brief explanation? – Kent Mar 11 '14 at 09:33
  • @tue: I need the conversion to happen after I put the values into the array. If I convert a to 97 (for example) then 9 and 7 would be loaded separately into my array. Kent: You're correct. It should have been 195 and 95. The program I copied output from averages them and I made a typo. It's fixed above. – reedms Mar 11 '14 at 16:43

1 Answers1

3

You can try:

awk 'BEGIN {
    FS=""
    for(n=0;n<256;n++)ord[sprintf("%c",n)]=n
}
{
    for (i=1;i<=NF;i++) ar[i]=ar[i]+ord[$i]
} 

END {
    for(y=1;y<=length(ar);y++) print ar[y]
}' file

Output:

195
95
Håkon Hægland
  • 39,012
  • 21
  • 81
  • 174