2013-02-25 62 views
0

因此,我正在尝试编写一个脚本,它将从命令行接受参数,并将所述变量用作字段参数进行打印。该脚本必须使用任何数字或NF。awk命令行将脚本参数作为变量来搜索特定字段

所以,

echo a b c | ./awkprint.sh 1 

将打印第一场(一)

,并

echo a b c | ./awkprint.sh NF 

将打印最后一个字段(C)。

下面是我对脚本

awk -v awkvar=$1 '{print $awkvar}' 

它完全适用于任何数量的,我在命令行中使用行......但是,只要我使用NF它似乎把它当作$ 0和印刷各个领域,所以我得到:

echo a b c | ./awkprint.sh NF 

a b c 

代替,

echo a b c | ./awkprint.sh NF 

c 

我在做什么错?

回答

0

这样做是因为字符串"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莫顿为指出:

#!/bin/bash 
awk -v awkvar=$1 '{print (awkvar == "NF" ? $NF : $awkvar)}' 

通知,不过,$0将会打印时awkvar不是可转换-TO-整数字符串,当它是"NF"

一个更合适的检查将是:

#!/bin/bash 
awk -v awkvar=$1 '{ 
    if (awkvar == "NF") { print; } 
    else if (int(awkvar) != 0) { print $awkvar; } 
    else { print "Error: invalid field specifier;" } 
}' 

您还可以检查int(awkvar) <= NF - 避免打印""

+0

但是,你会如何获得NF工作? – rbrow 2013-02-25 14:42:07

+0

'awk -v awkvar = $ 1'{print(awkvar ==“NF”?$ NF:$ awkvar)}'' – 2013-02-25 14:51:14

+0

@EdMorton这只是一个'if'的常见压缩,并没有回答'NF'不能正常工作的原因。 – Rubens 2013-02-25 14:52:29

相关问题