【问题标题】:How to print the result of a system command in awk如何在 awk 中打印系统命令的结果
【发布时间】:2019-11-16 04:37:36
【问题描述】:

我的 bash 脚本中有以下一行:

echo "foo" | awk -F"=" '{char=system("echo $1 | cut -c1");}{print "this is the result: "$char;}' >> output.txt

我想使用 awk 打印“foo”的第一个字母,这样我会得到:

this is the result: f

在我的输出文件中,但相反,我得到:

this is the result: foo

我做错了什么? 谢谢

【问题讨论】:

    标签: bash awk


    【解决方案1】:

    不,这不是system 命令在awk 中的工作方式。

    OP 的代码发生了什么:

    • 您在system 中给出了一个shell 命令,这很好(在某些情况下),但是在这个命令中存在一个问题,您应该像system("echo " $0" | cut -c1") 一样给出它以获得它的第一个字符并且您不需要有变量等保存其值并在awk中打印。
    • 您正试图将其结果保存到一个变量中,但它没有它的值(系统命令的值),而是它的状态。它不像这里的awk 中的shell 样式。
    • 所以你名为char 的变量将有0 值(这是来自system 命令的成功状态)并且当你打印$char 时它正在打印整行(因为在awk: @987654333 @ 表示打印整行)。


    您可以通过以下方式在单个 awk 中执行此操作:

    echo "foo" | awk '{print substr($0,1,1)}'
    

    或与 GNU awk 一起使用:

    echo "foo" | awk 'BEGIN{FS=""} {print $1}'
    

    【讨论】:

      【解决方案2】:

      你没有使用很多awk,同样可以使用printf

      $ echo "foo" | xargs printf "this is the result: %.1s\n"
      this is the result: f
      

      或者,直接

      $ printf "this is the result: %.1s\n" foo
      this is the result: f
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-26
        • 1970-01-01
        • 2014-04-04
        • 2021-10-19
        • 1970-01-01
        相关资源
        最近更新 更多