将参数传递给awk脚本文件

Mah*_*mam 31 unix linux awk

如果我想将参数传递给awk脚本文件,我该怎么做?

#!/usr/bin/awk -f

{print $1}
Run Code Online (Sandbox Code Playgroud)

这里我想打印从shell传递给脚本的第一个参数,如:

bash-prompt> echo "test" | ./myawkscript.awk hello
bash-prompt> hello
Run Code Online (Sandbox Code Playgroud)

Chr*_*our 55

awk $1引用中,记录中的第一个字段不像第一个字段那样bash.您需要使用ARGV此功能,请在此处查看官方字词.

脚本:

#!/bin/awk -f

BEGIN{
    print "AWK Script"
    print ARGV[1]
}
Run Code Online (Sandbox Code Playgroud)

演示:

$ ./script.awk "Passed in using ARGV"
AWK Script
Passed in using ARGV
Run Code Online (Sandbox Code Playgroud)

  • 比接受,简洁和正确的方式更好. (5认同)

fed*_*qui 27

您可以使用-v一个命令行选项,以提供脚本变量:

假设我们有一个像这样的文件script.awk:

BEGIN {print "I got the var:", my_var}
Run Code Online (Sandbox Code Playgroud)

然后我们像这样运行它:

$ awk -v my_var="hello this is me" -f script.awk
I got the var: hello this is me
Run Code Online (Sandbox Code Playgroud)

  • IMO,这是真正解决该问题的唯一答案。要添加此内容,如果脚本是可执行的,您仍然可以执行以下操作:`cat file | script.awk -v my_var =“你好,这是你” (2认同)

Ken*_*ent 15

你的哈希爆炸定义了脚本不是shell脚本,它是一个awk脚本.你不能在你的脚本中以bash的方式做到这一点.

还有,你做了什么:echo blah|awk ...不是经过paramenter,它管道echo命令的输出到另一个命令.

你可以尝试以下方式:

 echo "hello"|./foo.awk file -
Run Code Online (Sandbox Code Playgroud)

要么

var="hello"
awk -v a="$var" -f foo.awk file
Run Code Online (Sandbox Code Playgroud)

有了这个,你有afoo.awk中的var ,你可以使用它.

如果你想做一些像shell脚本接受$ 1 $ 2 vars的东西,你可以写一个小的shellcript来包装你的awk东西.

编辑

不,我没有误会你.

让我们举个例子:

让我们说,你x.awk有:

{print $1}
Run Code Online (Sandbox Code Playgroud)

如果你这样做:

echo "foo" | x.awk file
Run Code Online (Sandbox Code Playgroud)

它与:

echo "foo"| awk '{print $1}' file
Run Code Online (Sandbox Code Playgroud)

这里只有awk的输入file,你的echo foo没有意义.如果你这样做:

  echo "foo"|awk '{print $1}' file -
or
    echo "foo"|awk '{print $1}' - file
Run Code Online (Sandbox Code Playgroud)

awk接受两个输入(awk的参数)一个是stdin,一个是文件,在你的awk脚本中你可以:

echo "foo"|awk 'NR==FNR{print $1;next}{print $1}' - file
Run Code Online (Sandbox Code Playgroud)

这将首先foo从你的echo 打印出来,然后file当然这个例子中的column1 没有做任何实际工作,只需打印它们.

你当然可以有两个以上的输入,并且不检查NR和FNR,你可以使用

ARGC   The number of elements in the ARGV array.

ARGV   An array of command line arguments, excluding options and the program argument, numbered from zero to ARGC-1
Run Code Online (Sandbox Code Playgroud)

例如 :

echo "foo"|./x.awk file1 - file2
Run Code Online (Sandbox Code Playgroud)

然后你的"foo"是第二个arg,你可以在你的x.awk中得到它 ARGV[2]

echo "foo" |x.awk file1 file2 file2 -
Run Code Online (Sandbox Code Playgroud)

现在是ARGV案[4].

我的意思是,你echo "foo"|..的awk是stdin,它可能是awk的第一个或第n个"参数"/输入.取决于你放置-(stdin)的位置.你必须在你的awk脚本中处理它.