shell 脚本中的多行 awk 脚本

问题描述 投票:0回答:5
#!/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
5个回答
2
投票

当您想要传递要执行的脚本的文件名时,请使用

awk -f

这里您的

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

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

0
投票
  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

0
投票

这是等效的脚本

$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 脚本中。


0
投票

在 tcsh 中不知道,但在 bash 中也可以使用 heredoc :

#!/usr/bin/bash

awk -f <(cat - <<-'_EOF_'
BEGIN{c=0}{
      if($1=="Net"){print $0}

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

              }
_EOF_
) input_file.txt > output_file.txt


0
投票

shell 函数和 heredoc 都是可选的,因为多行

awk
脚本也可以裸露工作:

#!/bin/sh

awk '
  BEGIN {
    c = 0;
  }
  {
    # do stuff for every input line from a file
    # passed as command line parameter or stdin
  }
' "${@:--}"
© www.soinside.com 2019 - 2024. All rights reserved.