Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call a bash script with arguments and then have the script call an AWK program with those arguments?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading