Passing shell variable to awk script

I want to pass a shell variable to awk script :

# cat file
PSAPSR3                           3722000   91989.25          2         98
PSAPSR7                           1562000 77000.1875          5         95
PSAPUNDO                            92000  4087.5625          4         96

# NU="PSAPSR7";export NU
 
# awk '$1 == "$NU" {print}' file

But above command is not working...??? :wall: :wall: :wall:

Expected output :

PSAPSR7                           1562000 77000.1875          5         95

Thanks...

why not going with:

awk '$1=="PSAPSR7"' file

Thanks Pandeesh,

But I can't specify the hardcoded string, insted I need to use the variable only and provide value to awk command through the variable. It's script requirement.

this works:

pandeeswaran@ubuntu:~$ awk -v a=$NU '$1==a' file
PSAPSR7 1562000 77000.1875 5 95
pandeeswaran@ubuntu:~$ 
1 Like

Thanks Pandeesh,

These codes working the way I wanted...!!!

Cheers.....!!!

instead of using -v switch to pass the SHELL variable to the awklet ,you can use like below .

awk '$1==a' a=$NU input-file
1 Like

Is there any difference in performance between -v switch and awklet?

Just "More than one ways to do it " philosophy .. :))

---------- Post updated at 01:54 PM ---------- Previous update was at 01:42 PM ----------

One thing , if you are passing multiple variables to an awk script using -v switch you have to precede -v for each variable .something like below .

awk -v usr=$USER -v pass=$PASSWORD -v .....

less keystrokes

echo "" | awk '{print a b c}' a=12 b=13 c=14

I don't think in performance, but the difference is that with -v the variable "a" is available also in the BEGIN section. If you don't need that, then you can use the other option.

Also note that in this context is better to use double quotes. In shell assignments this is not needed, but this is not a shell assignment and the variable will be evaluated by the shell. To illustrate:

$ NU="Hello   There"
$ a=$NU
$ echo "$a"
Hello   There

$ awk -v a="$NU" 'BEGIN{print a}'
Hello   There

$ awk -v a=$NU 'BEGIN{print a}' 
awk: can't open file BEGIN{print a}
 source line number 1

$ awk 'BEGIN{print a}' a="$NU"

$ echo | awk '{print a}' a="$NU"
Hello   There

$ echo | awk '{print a}' a=$NU
awk: can't open file There
 source line number 1
$
1 Like