gpt4 book ai didi

linux - Awk 命令行将参数编写为变量以搜索特定字段

转载 作者:太空宇宙 更新时间:2023-11-04 04:18:13 25 4
gpt4 key购买 nike

所以我试图编写一个脚本,该脚本将从命令行获取参数并使用所述变量作为要打印的字段参数。该脚本必须使用任意数字或 NF。

所以,

echo a b c | ./awkprint.sh 1 

将打印第一个字段 (a)

并且,

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

我做错了什么?

最佳答案

这样做是因为字符串 "NF"转换为0 .

awk转换过程指出任何无法转换为有效数字的字符串的计算结果为 0 ,因此,给你print $0 .

来自 man awk :

Variable Typing And Conversion

  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 :

RETURN VALUE

  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)}'

但请注意,$0awkvar 时都会打印不是可转换为整数的字符串,当它是 "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 -- 避免打印 "" .

关于linux - Awk 命令行将参数编写为变量以搜索特定字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069246/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com