1

我可以使用 bash 命令替换技术在单行中创建一个 awk 变量吗?这是我正在尝试的,但有些不对劲。

awk -v AVG=$(uptime|awk '{print $(NF-2)}') '{ if ( AVG >= 1 ) print "there is a load"  }'

也许是因为命令替换使用了 Awk(尽管我对此表示怀疑)?也许这太“盗梦空间”了?GNU awk 3.1.7

4

4 回答 4

3

为什么要在这里使用变量?就 AWK 读取而言stdin,除非您明确指定相反的内容,否则这应该是一种更可取的方式:

$ uptime | awk '$(NF-2) >= 1 { print "there is a load" }'
there is a load
于 2013-12-21T22:35:59.213 回答
1

你的命令没有错。您的命令正在等待输入,这是它没有被执行的唯一原因!

例如:

$ awk -v AVG=$(uptime|awk '{print $(NF-2)}') '{ if ( AVG >= 0 ) print "there is a load"  }'
abc                 ## I typed.
there is a load     ## Output.

只需按照专家的建议在您的命令中包含 BEGIN 即可!

$ awk -v AVG=$(uptime|awk '{print $(NF-2)}') 'BEGIN{ if ( AVG >= 0 ) print "there is a load"  }'
there is a load
于 2013-12-22T06:19:54.910 回答
0

这个:

awk -v AVG=$(uptime|awk '{print $(NF-2)}') '{ if ( AVG >= 1 ) print "there is a load"  }'

正如其他人所说,需要一个 BEGIN :

awk -v AVG=$(uptime|awk '{print $(NF-2)}') 'BEGIN{ if ( AVG >= 1 ) print "there is a load"  }'

而且,你不需要调用 awk 两次,因为它可以写成:

awk -v uptime=$(uptime) 'BEGIN{ n=split(uptime,u); AVG=u[n-2]; if ( AVG >= 1 ) print "there is a load"  }'

或更可能是您想要的:

uptime | awk '{ AVG=$(NF-2); if ( AVG >= 1 ) print "there is a load"  }'

可以简化为:

uptime | awk '$(NF-2) >= 1 { print "there is a load"  }'
于 2013-12-22T14:39:42.520 回答
0

由于最后一个 awk 命令没有输入文件,因此您只能BEGIN对该脚本使用子句。因此,您可以尝试以下方法:

awk -v AVG=$(uptime|awk '{print $(NF-2)}') 'BEGIN{ if ( AVG >= 1 ) print "there is a load"  }'
于 2013-12-21T22:28:48.890 回答