简体   繁体   English

如何在系统命令中使用awk脚本的shell变量?

[英]How do I use shell variables of awk script in system command?

I am troubleing in coverting hex to decimal from txt file using awk. 我在使用awk从txt文件中将十六进制转换为十进制时遇到了麻烦。

I want to do like this 我想这样做

awk -F' '   '{   system("echo '$((16#"$1"))'") '} $file_name

but not work... then I try other code 但没有工作...然后我尝试其他代码

awk -F' ' -v var="\"echo \x27\$((16#" '{var=var$1"))\x27\"" system(var) }' $file_name

also not work. 也行不通。 but print var then enter image description here 但是打印var然后在这里输入图像描述

what should i do? 我该怎么办?

Using awk 使用awk

To use GNU awk to convert hex to decimal: 要使用GNU awk将十六进制转换为十进制:

$ echo '0xFFFFFFFE' | awk -n '{printf "%i\n",$1}'
4294967294

Or: 要么:

$ x='0xFFFFFFFE'
$ awk -n -v x="$x"  'BEGIN{printf "%i\n",x}'
4294967294

Or: 要么:

$ x='0xFFFFFFFE'; awk -v x="$x"  'BEGIN{print strtonum(x)}'
4294967294

To convert hex to decimal using bash: 要使用bash将十六进制转换为十进制:

$ echo $((0xFFFFFFFE))
4294967294

Limitations: 限制:

1. GNU awk is limited to 52-bit integers.

2. The above could be extended to perform two's-complement arithmetic but it hasn't.

To avoid both these limitations, see the python solution below: 要避免这些限制,请参阅下面的python解决方案:

Using python 使用python

Awk does not handle long integers. Awk不处理长整数。 For long integers, consider this python script: 对于长整数,请考虑以下python脚本:

$ cat n.py
#!/usr/bin/python3
import sys
def h(x):
        x = int(x, 16)
        return x if x < 2**63 else x - 2**64

for line in sys.stdin:
        print(*[h(x) for x in line.split()])

Let's use this input file: 让我们使用这个输入文件:

$ cat file
FFFFFFFFFFFFFFFF EFEFEFEFEFEFEFEF

When we run our script, we find: 当我们运行脚本时,我们发现:

$ python3 n.py <file
-1 -1157442765409226769

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM