【问题标题】:multiline awk script inside shell scriptshell 脚本中的多行 awk 脚本
【发布时间】:2021-11-11 09:28:43
【问题描述】:
#!/usr/bin/tcsh

 cmd='BEGIN{c=0}{
      if($1=="Net"){print $0}

       if($1=="v14")
       {
         if($4>=200)
           {print "Drop more than 200 at "$1}
          }

              }'

         
awk -f "$cmd" input_file.txt > output_file.txt

我正在尝试执行其中包含多行 awk 脚本的 shell 脚本。 将 awk 脚本(尤其是多行 awk 脚本)存储到变量 cmd 中,然后在 awk -f "$cmd" input_file.txt > output_file.txt 中执行该 cmd。

这给出了如下错误

     awk: fatal: can't open source file `BEGIN{c=0}{
          if($1=="Net"){print $0}

           if($1=="v14")
           {
             if($4>=200)
              {print"Drop more than 200 at $1}
               }

                }' for reading (No such file or directory)

我的任务是如何执行其中包含多行 awk 脚本的 shell 脚本? 你能帮我解决这个问题吗?即使在谷歌/参考手册中搜索后我也无法弄清楚?

【问题讨论】:

标签: shell awk scripting tcsh


【解决方案1】:

当你想传递一个文件名让脚本执行时,你使用awk -f

这里您的 awk 脚本是一个内联字符串,因此只需删除 -f 选项即可解决您的问题。

awk "$cmd" input_file.txt > output_file.txt

【讨论】:

  • 这实际上帮助我解决了错误。但脚本输出不正确。 awk 脚本未正确执行。可能将 awk 脚本设置为 shelll 变量是个坏主意。有什么方法可以执行包含多行 awk 脚本的 shell 脚本。
  • @Ajayshifu 您的 awk 脚本需要修复。调试您的 awk 脚本。见:How to debug an AWK script
  • @Gris Lea,感谢您提供的信息。
【解决方案2】:
  1. 不要编写 [t]csh 脚本,查看 https://www.google.com/search?q=csh+why+not 的许多结果中的任何一个,使用 Bourne 派生的 shell,如 bash。
  2. 不要将 awk 脚本存储在 shell 变量中,然后让 awk 解释该变量的内容,只需将脚本存储在函数中并调用它即可。

所以,做这样的事情:

#!/usr/bin/env bash

foo() {
    awk '
        { print "whatever", $0 }
    ' "${@:--}"
}

foo input_file.txt > output_file.txt

【讨论】:

【解决方案3】:

这是等效的脚本

$1=="Net"
$1=="v14" && $4>=200 {print "Drop more than 200 at "$1}

保存到文件中,例如test.awk 并运行为

$ awk -f test.awk input_file > output_file

或者,对于简单的一次性脚本,您可以只是

$ awk '$1=="Net"; $1=="v14" && $4>=200 {print "Drop more than 200 at "$1}' input_file > output_file

显然上述行也可以插入到 shell 脚本中。

【讨论】:

  • 在我的情况下,我需要将该 awk 脚本嵌入到其他人编写的 shell 脚本中。所以我的问题实际上是“如何将多行 awk 脚本嵌入到 shell 脚本中并执行 shell 脚本?”
  • 一个脚本可以像awk一样调用其他脚本,也可以在awk调用中内联脚本。不确定您要解决的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-19
  • 1970-01-01
  • 2013-04-18
  • 2017-07-25
相关资源
最近更新 更多