[英]Parse log containing hex character codes using awk or xxd or something
i have a file that looks like this:我有一个看起来像这样的文件:
.
.
.
15 02 2013 12:05:07 [DBG] vspd[3327]: VSP 0: RX 452B30303032340D
15 02 2013 12:05:07 [DBG] vspd[3327]: VSP 0: WX 452B30303032340D
Sniffer log of serial port communication.串口通讯的嗅探器日志。
How can i automatically translate hex char codes to string?如何自动将十六进制字符代码转换为字符串?
I tried to use some thing like this:我尝试使用这样的东西:
cat vspd.log | awk -F'(RX|WX)[[:space:]]*' '{print $2}' | awk 'BEGIN { FS = "" }{for (i = 1; i < NF; i = i + 1) a=$i$i+1;printf "%s", a; print}' | xxd -r
But it gives only very partial success, i think i messed something with pipes.但它只取得了非常部分的成功,我想我把管道弄乱了。
The question is how can i convert问题是我如何转换
tail -f file.log | awk -F'(RX|WX)[[:space:]]*' '{print $2}'
Into something readable?变成可读的东西?
Perl solution: Perl解决方案:
#!/usr/bin/perl
while (<>) {
($prefix, $hex) = /^(.*) (.*)$/;
$hex =~ s/(..)/chr hex $1/ge;
print "$prefix $hex\n";
}
Output:输出:
15 02 2013 12:05:07 [DBG] vspd[3327]: VSP 0: RX E+00024
15 02 2013 12:05:07 [DBG] vspd[3327]: VSP 0: WX E+00024
Note: You might need to remove the final \\x0D from the strings.注意:您可能需要从字符串中删除最后的 \\x0D。
You can indeed get there with awk
and xxd
, here is an example:您确实可以使用
awk
和xxd
到达那里,这是一个示例:
<infile awk -F'(RX|WX)[[:space:]]*' '{ print $2 }' | xxd -p -r | awk 1 RS='\r'
Output:输出:
E+00024
E+00024
With GNU awk you can use strtonum()
to convert the hexadecimals, eg:使用 GNU awk,您可以使用
strtonum()
来转换十六进制,例如:
function hex2str(n) {
s = ""
for(i=1; i<=length(n)-1; i+=2)
s = s sprintf("%c", strtonum("0x" substr(n, i, 2)));
return s
}
Then you could do the conversion like this:然后你可以像这样进行转换:
{ $NF = hex2str($NF) }
Here's a complete example:这是一个完整的例子:
<infile awk '
function hex2str(n) {
s = ""
for(i=1; i<=length(n)-1; i+=2)
s = s sprintf("%c", strtonum("0x" substr(n, i, 2)));
return s
}
{ $NF = hex2str($NF) }
1
'
Output:输出:
15 02 2013 12:05:07 [DBG] vspd[3327]: VSP 0: RX E+00024
15 02 2013 12:05:07 [DBG] vspd[3327]: VSP 0: WX E+00024
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.