首页 > 解决方案 > shell 脚本中的多行 awk 脚本

问题描述

#!/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 脚本?你能帮我解决这个问题吗,因为即使在谷歌/参考手册中搜索后我也无法弄清楚?

标签: shellawkscriptingtcsh

解决方案


awk -f当您想要传递要执行的脚本的文件名时使用。

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

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

推荐阅读