简体   繁体   English

将命令行参数传递给gawk脚本

[英]passing command line argument to gawk script

I have a script chk.awk to which I want to pass some command line arguments. 我有一个脚本chk.awk ,我想向其中传递一些命令行参数。 It has awk statements, sed command etc. Just for example I have taken a small program below to which I want to pass command line arguments. 它具有awk语句, sed命令等。仅举例来说,我在下面做了一个小程序,要将命令行参数传递给该小程序。

#!/bin/bash
var1=$1
gawk '
BEGIN {
        printf "argc = %d\n argv0=%s\n argv1=%s\n var1=%s\n",ARGC,ARGV[0],ARGV[1],$var1
}'

But when I try : 但是当我尝试:

$ sh chk.awk 10 20
argc = 1
argv0=gawk
argv1=
var1=

Above I tried to display the command line arguments by both ways ie argv & $1 , but none of them work. 上面我试图通过argv$1两种方式显示命令行参数,但是它们都不起作用。 Can anyone let me know where I am going wrong here? 谁能让我知道我在哪里错了? What is the correct way to do that? 正确的方法是什么?

The problem is that you give arguments to the shell script, but not to the awk script. 问题是您将参数提供给shell脚本,而不是awk脚本。 You must add "$@" to the call of gawk . 您必须在gawk的调用中添加"$@"

#!/bin/bash
var1=$1
gawk '
BEGIN {
    printf "argc = %d\n argv0=%s\n argv1=%s\n var1=%s\n",ARGC,ARGV[0],ARGV[1],$var1
}' "$@" 

Otherwise you will your arguments in the shell-script and they will be not passed to gawk . 否则,您会将您的参数放在shell脚本中,并且不会将它们传递给gawk

Update 1 更新1

If you have additional args (eg filenames that are to be processed), you must remove the first portition of args first (in the BEGIN section): 如果您还有其他args(例如要处理的文件名),则必须先删除args的第一个分区(在BEGIN部分中):

#!/bin/bash
var1=$1
gawk '
BEGIN {
    printf "argc = %d\n argv0=%s\n argv1=%s\n var1=%s\n",ARGC,ARGV[0],ARGV[1],$var1;
    delete ARGV[1]
}' "$@" filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM