将字段(位置变量)的值分配给 gawk/awk 中的用户定义变量
我正在创建一个名为“size”的变量,并尝试从 gawk 位置变量为其分配一个值。但是,这似乎不起作用。在下面的示例中,我尝试将字段 4 的值存储到变量“size”中。当我打印变量大小时,会打印整行,而不是仅打印字段值 4.
如何将字段值保存到变量中以供以后使用?
prompt> echo "Live in a big city" | gawk '/Live/ {size=$4; print $size}'
输出如下: 生活在大城市
我只想看到这个:
大
I am creating a variable called "size" and trying to assign a value to it from gawk positional variable. But, that does not seem to work. In the example below, I am trying to store the value of field 4 into a variable "size". When I print the variable size, entire line is printed instead just the filed 4.
How can I save the filed value into a variable for later use?
prompt> echo "Live in a big city" | gawk '/Live/ {size=$4; print $size}'
The following is outputted:
Live in a big city
I would like to see just this:
big
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
省略美元符号。 awk 就像 C 语言,而不像 shell 或 perl,在这些语言中您不需要任何额外的标点符号来取消引用变量。您只需使用美元符号即可获取当前行第 n 个字段的值。
打印整行的原因是:awk 变量
size
被分配了值big
。然后,在 print 语句中,awk 取消引用size
变量并尝试print $big
。字符串“big”被解释为整数,并且由于它不以任何数字开头,因此被视为数字 0。因此您将得到print $0
,从而得到完整的行。Leave out the dollar sign. awk is like C, not like shell or perl, where you don't need any extra punctuation to dereference a variable. You only use a dollar sign to get the value of the n'th field on the current line.
The reason you get the whole line printed is this: the awk variable
size
is assigned the valuebig
. Then, in the print statement, awk dereferences thesize
variable and attemptsprint $big
. The string "big" is interpreted as an integer and, as it does not begin with any digits, it is treated as the number 0. So you getprint $0
, and hence the complete line.