Substitute variable inside nawk

Hi,

I need to set "prd" in the below command to a unix variable

nawk '/^#/ {next} FNR==NR {prd[$0];next} !($0 in prd)'

So, this is what i did

fname=prd   // unix shell variable

nawk -v fname=$fname '/^#/ {next} FNR==NR {fname[$0];next} !($0 in fname)'

But the value of fname i.e "prd" is not getting substituted in the command.

Can you tell me why ?

OS: SunOS mymac 5.10 Generic_150400-09 sun4v sparc SUNW,SPARC-Enterprise-T5220

You have 2 variables called 'fname':

  1. Scalar fname passed into awk by: -v fname=$fname
  2. Array fname you're populating with $0: fname[$0]

What's the purpose of passing a scalar fname to awk?
What exactly are you after?

As i explained in the OP all i want is instead of using "prd" in the command i wish to use unix variable fname.

So, the problem is the below is not working !!

  1. Scalar fname passed into awk by: -v fname=$fname

Can you now help ?

Maybe this will show you some light

echo 'Show me the content of $fname' | awk -v fname=$fname '{print fname}'

If you can see prd in your stdout, then that's not the problem.

Let me rephrase my question.

I am using the below code to find the difference between two files prod.properties and back.properties.

nawk '/^#/ {next} NR==FNR {prod[$0]=$0;next} {if ($0 in prod) { delete prod[$0] } else {print }}; END {for (i in prod) print prod}' prod.properties back.properties

Source: Comparing two files issue. Post: 302903183

Now, the requirement is to automate the above code so that it does the job for any two file names not neccessarily prod.properties and back.properties

I am passing any two filenames like this.

./check.sh filename1.properties filename2.txt

and reading them in variables file1=$1, file2=$2.

So, how can I achieve that ?

Assuming that check.sh contains:

nawk '/^#/ {next} NR==FNR {prod[$0]=$0;next} {if ($0 in prod) { delete prod[$0] } else {print }}; END {for (i in prod) print prod}' prod.properties back.properties

change it to:

file1="$1"
file2="$2"
nawk '/^#/ {next} NR==FNR {prod[$0]=$0;next} {if ($0 in prod) { delete prod[$0] } else {print }}; END {for (i in prod) print prod}' "$file1" "$file2"

or just:

nawk '/^#/ {next} NR==FNR {prod[$0]=$0;next} {if ($0 in prod) { delete prod[$0] } else {print }}; END {for (i in prod) print prod}' "$1" "$2"

or even:

nawk '/^#/ {next} NR==FNR {prod[$0]=$0;next} {if ($0 in prod) { delete prod[$0] } else {print }}; END {for (i in prod) print prod}' "$@"

So the "prod" inside nawk is just a variable ?

I thought it has some relation with the prod.properties

Please confirm.

prod is just an array in your script, there is no relation with file prod.properties

Yes, you are right. That array name within awk is a variable that you can call what you like. It's not bad an idea to use some mnemonic name indicating what it's used for, for e.g. later debugging.