将参数传递到awk脚本文件 [英] Pass parameter to an awk script file

查看:158
本文介绍了将参数传递到awk脚本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If I want to pass a parameter to an awk script file, how can I do that ?

#!/usr/bin/awk -f

{print $1}

在这里,我想打印从外壳传递到脚本的第一个参数,例如:

Here I want to print the first argument passed to the script from the shell, like:

bash-prompt> echo "test" | ./myawkscript.awk hello
bash-prompt> hello

推荐答案

您的哈希爆炸定义的脚本不是shell脚本,而是awk脚本.您无法在脚本中以bash方式进行操作.

your hash bang defines the script is not shell script, it is an awk script. you cannot do it in bash way within your script.

另外,您所做的:echo blah|awk ...不是传递参数,它会将echo命令的输出通过管道传递到另一个命令.

also, what you did : echo blah|awk ... is not passing paramenter, it pipes the output of echo command to another command.

您可以在下面尝试以下方式:

you could try these way below:

 echo "hello"|./foo.awk file -

var="hello"
awk -v a="$var" -f foo.awk file

这样,您在foo.awk中就有var a,就可以使用它.

with this, you have var a in your foo.awk, you could use it.

如果您想执行类似shell脚本之类的操作,请接受$ 1 $ 2 vars,则可以编写一个小的shellscript来包装您的awk内容.

if you want to do something like shell script accept $1 $2 vars, you can write a small shellscript to wrap your awk stuff.

编辑

不,我没有误会你.

让我们举个例子:

假设您的x.awk具有:

{print $1}

如果您这样做:

echo "foo" | x.awk file

它与:

echo "foo"| awk '{print $1}' file

此处,awk的输入仅为file,您的echo foo没有任何意义.如果您这样做:

here the input for awk is only file, your echo foo doesn't make sense. if you do:

  echo "foo"|awk '{print $1}' file -
or
    echo "foo"|awk '{print $1}' - file

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

awk takes two input (arguments for awk) one is stdin one is the file, in your awk script you could:

echo "foo"|awk 'NR==FNR{print $1;next}{print $1}' - file

这将从您的回声中首先打印foo,然后从file中的column1当然不执行任何实际工作,仅打印所有内容.

this will print first foo from your echo, then the column1 from file of course this example does nothing actual work, just print them all.

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

you can of course have more than two inputs, and don't check the NR and FNR, you could use the

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

例如:

echo "foo"|./x.awk file1 - file2

然后您的"foo"是第二个参数,您可以通过ARGV[2]

then your "foo" is the 2nd arg, you can get it in your x.awk by ARGV[2]

echo "foo" |x.awk file1 file2 file2 -

现在是ARGV [4]案件.

now it is ARGV[4] case.

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

I mean, your echo "foo"|.. would be stdin for awk, it could by 1st or nth "argument"/input for awk. depends on where you put the -(stdin). You have to handle it in your awk script.

这篇关于将参数传递到awk脚本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆