Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass parameter to an awk script file

Tags:

linux

unix

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 
like image 734
Mahmoud Emam Avatar asked Apr 12 '13 11:04

Mahmoud Emam


People also ask

How do you pass command line arguments in awk?

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.

How do you pass variables in a script?

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.

How do I pass multiple variables in awk?

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.


1 Answers

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 
like image 134
Chris Seymour Avatar answered Oct 01 '22 19:10

Chris Seymour