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
You can use
-v
as a command-line option to provide a variable to the script:Say we have a file script.awk like this:
Then we run it like this:
In
awk
$1
references the first field in a record not the first argument like it does inbash
. You need to useARGV
for this, check out here for the offical word.Script:
Demo:
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.
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:
or
with this, you have var
a
in your foo.awk, you could use it.if you want to do something like shell script accept $1 $2 vars, you can write a small shellscript to wrap your awk stuff.
EDIT
No I didn't misunderstand you.
let's take the example:
let's say, your
x.awk
has:if you do :
it is same as:
here the input for awk is only
file
, your echo foo doesn't make sense. if you do:awk takes two input (arguments for awk) one is stdin one is the file, in your awk script you could:
this will print first
foo
from your echo, then the column1 fromfile
of course this example does nothing actual work, just print them all.you can of course have more than two inputs, and don't check the NR and FNR, you could use the
for example :
then your "foo" is the 2nd arg, you can get it in your x.awk by
ARGV[2]
now it is ARGV[4] case.
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.