【问题标题】:Does awk -v accept command substitution?awk -v 是否接受命令替换?
【发布时间】:2013-12-21 22:22:42
【问题描述】:

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

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

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

【问题讨论】:

    标签: bash awk command-substitution


    【解决方案1】:

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

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

    【讨论】:

    • 你能修正你的拼写错误吗? (NF-2) 缺少 $ 符号。应该是 $(NF-2)。
    【解决方案2】:

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

    例如:

    $ 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
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        这个:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2013-03-15
          • 2014-02-06
          • 2016-03-19
          • 1970-01-01
          • 1970-01-01
          • 2014-01-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多