#!/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 脚本? 你能帮我解决这个问题吗,因为即使在谷歌/参考手册中搜索后我也无法弄清楚?
当您想要传递要执行的脚本的文件名时,请使用
awk -f
。
这里您的
awk
脚本是内联字符串,因此只需删除 -f
选项即可解决您的问题。
awk "$cmd" input_file.txt > output_file.txt
所以,做这样的事情:
#!/usr/bin/env bash
foo() {
awk '
{ print "whatever", $0 }
' "${@:--}"
}
foo input_file.txt > output_file.txt
这是等效的脚本
$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 脚本中。
在 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
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
}
' "${@:--}"