简体   繁体   English

BEGIN块中的十六进制字符

[英]Hex character in BEGIN block

I can print a hex character in the process block 我可以在进程块中打印十六进制字符

$ awk '{printf "%c", $0}' <<< 0x21
!

However the same character will not print in the BEGIN block 但是,相同的字符不会在BEGIN块中打印

$ awk 'BEGIN {printf "%c", 0x21}'
0

How can I print a hex character in the BEGIN block? 如何在BEGIN块中打印十六进制字符?

GNU awk supports hex notation but traditional awk does not . GNU awk支持十六进制表示法,但传统的awk支持。 The POSIX standard for awk is here and it states: awk的POSIX标准在这里 ,它指出:

An integer constant cannot begin with 0x or include the hexadecimal digits 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', or 'F'. 整数常量不能以0x开头或包含十六进制数字'a','b','c','d','e','f','A','B','C','D ','E'或'F'。

Here is one method that uses bash to supply the constant string that you want to a POSIX awk: 这是一个使用bash为POSIX awk提供你想要的常量字符串的方法:

awk -v p=$'\x21' 'BEGIN {printf "%c", p}'

References 参考

  • -vp=string

    The -v option allows awk variables to be defined via the command line. -v选项允许通过命令行定义awk变量。 This is documented in the POSIX spec under "options" here . 这是在POSIX规范下的“选项”记录在这里

  • $'\\x21'

    The $'...' construct allows many special characters to be added to bash strings. $'...'构造允许将许多特殊字符添加到bash字符串中。 Here, we add a hexadecimal. 在这里,我们添加一个十六进制。 This is documented in the bash manual here . 这是在记录bash手册在这里

When reading a string awk will recognize hex numbers. 当读取字符串时,awk将识别十六进制数字。

When reading a number awk will not recognize hex numbers, it will toss out everything starting with the first non number. 当读取数字时,awk将无法识别十六进制数字,它将从第一个非数字开始抛出所有内容。

So with the first example $0 is a string and all is well. 因此,对于第一个示例, $0是一个字符串,一切都很好。 With the second example x21 is tossed out and 0 is left. 在第二个例子中, x21被抛出并且剩下0 A workaround is to pass 0x21 as a string 解决方法是将0x21作为字符串传递

$ awk 'BEGIN {printf "%c", +"0x21"}'
!

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

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