awk convert ASCII to integer in context of awk command

妖精的绣舞 提交于 2021-01-28 06:08:56

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/22319039/awk-convert-ascii-to-integer-in-context-of-awk-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!