提取 AWK 中的位标志和"and($1,0x1)"语句

  • 本文关键字:0x1 语句 and 标志 提取 AWK awk
  • 更新时间 :
  • 英文 :


有人能解释一下像and($1,1)这样的语句在AWK中的含义,给出一些典型的用法示例,并可能解释下面代码片段中的行为吗?我知道这样的语句可以用来提取位标志,但我在AWK用户指南中找不到任何关于如何正确使用它的参考

echo "1n3" | gawk '{if (and($1, 0x2)) print}'
3
echo "1n3" | gawk '{if (and($1, 0x1)) print}'
1
3
echo "1n3" | gawk '{if (and($1, 1)) print}'
1
3
echo "1n3" | gawk '{if (and($1, 2)) print}'
3
echo "1n3" | gawk '{if (and($1, 3)) print}'
1
3
函数调用and($1, 1)$1为奇数时返回1(true(,否则返回O(false(。例如
echo $'1n2n3n4' | awk '{print and($1, 1)}'

输出:

1
0
1
0

在AWK用户指南中找不到任何关于如何正确使用它的参考资料。

来自man awk

Bit Manipulations Functions
Starting with version 3.1 of gawk, the following bit manipulation functions are available. They work by converting double-precision floating point values to uintmax_t integers, doing the operation, and then converting the result back to floating point. The functions are:
and(v1, v2)
Return the bitwise AND of the values provided by v1 and v2.
compl(val)
Return the bitwise complement of val.
lshift(val, count)
Return the value of val, shifted left by count bits.
or(v1, v2)
Return the bitwise OR of the values provided by v1 and v2.
rshift(val, count)
Return the value of val, shifted right by count bits.
xor(v1, v2)
Return the bitwise XOR of the values provided by v1 and v2. 

请注意,这需要gawk3.1或更高版本,因此依赖它的代码在其他版本中可能会失败。

最新更新