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
$ awk 'BEGIN {printf "%c", 0x21}'
0
How can I print a hex character in the BEGIN block?
GNU awk
supports hex notation but traditional awk
does not . The POSIX standard for awk
is here and it states:
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'.
Here is one method that uses bash
to supply the constant string that you want to a POSIX awk:
awk -v p=$'\x21' 'BEGIN {printf "%c", p}'
-vp=string
The -v
option allows awk
variables to be defined via the command line. This is documented in the POSIX spec under "options" here .
$'\\x21'
The $'...'
construct allows many special characters to be added to bash
strings. Here, we add a hexadecimal. This is documented in the bash
manual here .
When reading a string awk will recognize hex numbers.
When reading a number awk will not recognize hex numbers, it will toss out everything starting with the first non number.
So with the first example $0
is a string and all is well. With the second example x21
is tossed out and 0
is left. A workaround is to pass 0x21
as a string
$ awk 'BEGIN {printf "%c", +"0x21"}'
!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.