Reputation: 3647
I have a script chk.awk
to which I want to pass some command line arguments. 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.
#!/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 i.e. argv
& $1
, but none of them work. Can anyone let me know where I am going wrong here? What is the correct way to do that?
Upvotes: 0
Views: 473
Reputation: 64563
The problem is that you give arguments to the shell script, but not to the awk script.
You must add "$@"
to the call of 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
.
Update 1
If you have additional args (e.g. filenames that are to be processed),
you must remove the first portition of args first (in the BEGIN
section):
#!/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
Upvotes: 1