这样做是因为字符串"NF"
被转换为0
.
awk
转换过程表明,任何无法转换为有效数字的字符串都会计算为0
,因此,给你print $0
.
来自man awk
:
变量类型和转换
Variables and fields may be (floating point) numbers, or
strings, or both. How the value of a variable is inter‐
preted depends upon its context. If used in a numeric
expression, it will be treated as a number; if used as a
string it will be treated as a string.
...
When a string must be converted to a number, the conversion
is accomplished using strtod(3).
从man strtod
:
返回值
These functions return the converted value, if any.
...
If no conversion is performed, zero is returned and the
value of nptr is stored in the location referenced by
endptr.
做你想做的事,你可以写——正如@Ed Morton所指出的:
#!/bin/bash
awk -v awkvar=$1 '{print (awkvar == "NF" ? $NF : $awkvar)}'
但是请注意,$0
当awkvar
它不是可转换为整数的字符串时和它是"NF"
.
更合适的检查是:
#!/bin/bash
awk -v awkvar=$1 '{
if (awkvar == "NF") { print; }
else if (int(awkvar) != 0) { print $awkvar; }
else { print "Error: invalid field specifier;" }
}'
您也可以检查 if int(awkvar) <= NF
-- 以避免打印""
。