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
Arguments given at the end of the command line to awk are generally taken as filenames that the awk script will read from. To set a variable on the command line, use -v variable=value , e.g. This would enable you to use num as a variable in your script. The initial value of the variable will be 10 in the above example.
Arguments can be passed to the script when it is executed, by writing them as a space-delimited list following the script file name. Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth. The variable $0 references to the current script.
awk programming -Passing variable to awk for loop awk: BEGIN -------- <some code here> END{ ----------<some code here> for(N=0; N<H; N++) { for(M=5; M<D; M++) print "\t" D ""; } ----- } ... Discussion started by ctrld and has been viewed 2,403 times.
In awk
$1
references the first field in a record not the first argument like it does in bash
. You need to use ARGV
for this, check out here for the offical word.
Script:
#!/bin/awk -f BEGIN{ print "AWK Script" print ARGV[1] }
Demo:
$ ./script.awk "Passed in using ARGV" AWK Script Passed in using ARGV
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With