I have a bash script named run.sh which contains this:
#!/bin/bash
awk -f filter NAV.TXT
filter is this awk program:
BEGIN { FS = OFS = "\t" }
($1 == "PLT") && ($2 == "5") && ($3 == "US") && ($4 == "1") && ($2 == "5" || $2 == "7") { print; }
Unfortunately, everything is hardcoded in that program. I want to replace all those (hardcoded) strings with parameters and pass into the program values for the parameters.
I imagine calling run.sh something like this:
bash run.sh PLT 5 US 1 5 7
And then inside run.sh it calls the filter program, passing to it the arguments. The filter program then uses those passed-in values. How to do this?
>Solution :
awk accepts variable definitions with -v or as file arguments that look like var=value.
So you can rewrite filter as:
BEGIN { FS = OFS = "\t" }
($1 == arg1) && ($2 == arg2) && ($3 == arg3) && ($4 == arg4) && ($2 == arg5 || $2 == arg6) { print; }
then invoke awk as:
awk -v arg1=PLT -v arg2=5 -v arg3=US \
-v arg4=1 -v arg5=5 -v arg6=7 \
-f filter NAV.TXT
or
awk -f filter NAV.TXT \
arg1=PLT arg2=5 arg3=US arg4=1 arg5=5 arg6=7