awk在awk命令的上下文中将ASCII转换为整数 [英] awk convert ASCII to integer in context of awk command

查看:179
本文介绍了awk在awk命令的上下文中将ASCII转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对使用ASCII符号编码的值的文件进行一些操作.

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!

我想使用awk脚本将它们转换为整数值,然后进行进一步的处理.我查看并找到了一种将ASCII转换为整数的方法:

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.

示例输出为:

195
95

如果我使用这样的测试文件(不包含上面的代码),我可以使它工作:

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

11
22

和代码:

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]}'

我得到了预期的结果:

3
3

有人对如何将ASCII转换为整数然后将其传递到我的awk语句的其余部分提出建议吗?

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

推荐答案

您可以尝试:

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

输出:

195
95

这篇关于awk在awk命令的上下文中将ASCII转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆