1

I am trying to insert the output below into the variable x. The output is a string. I have done this before.

k="psz"

And when I do this it works and i get the expected output when doing echo $x

x=$( awk -v a="k" -F '[:,]' '{ if($1 == "psz")  print $5 }' /etc/passwd )

But when i try to use this one below it doesn't work

x=$( awk -v a="k" -F '[:,]' '{ if($1 == a)  print $5 }' /etc/passwd )

It does not work, echo $x gives me a blank line.

Panagiss
  • 3,154
  • 2
  • 20
  • 34

1 Answers1

3

You are setting a with the string k and not the value of variable $k. If you set it right, the code will work fine. Look:

k='accdias'
x=$(awk -va=$k 'BEGIN{FS=":"} $1==a {print $5}' /etc/passwd)
echo $x
Antonio Dias

I'm editing this to show another way of passing variable values to your awk program without using -v:

k='accdias'
x=$(awk 'BEGIN{FS=":"} $1==ARGV[2] {print $5}' /etc/passwd $k)
echo $x
Antonio Dias

On the above code ARGV[0] will be set to awk, ARGV[1] will be set to /etc/passwd, and finally ARGV[2] will be set to $k value, which is accdias on that example.


Edits from Ed Morton (see comments below):

k='accdias'
x=$(awk -v a="$k" 'BEGIN{FS=":"} $1==a {print $5}' /etc/passwd)
echo "$x"
Antonio Dias

k='accdias'
x=$(awk 'BEGIN{FS=":"; a=ARGV[2]; ARGV[2]=""; ARGC--} $1==a {print $5}' /etc/passwd "$k")
echo "$x"
Antonio Dias
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
accdias
  • 5,160
  • 3
  • 19
  • 31
  • yea you are right i found it. Do you know how i can put an if else into the awk? – Panagiss Nov 27 '19 at 20:08
  • 1
    you have the right idea for `if/else` in your OP. Just `{ if($1 == a) {print $5} else {print "no match"} }` . Good luck. – shellter Nov 27 '19 at 20:13
  • 1
    No worries. About the if/else, something like this will do it ```if (condition){commands} else {commands}```. – accdias Nov 27 '19 at 20:14
  • on the second answer you gave... if you pass the ARGV[2] into $1, how will you be able to use the first field of each record ? the $1 variable – Panagiss Nov 27 '19 at 20:42
  • 2
    You must quote your shell variables (see https://mywiki.wooledge.org/Quotes) and if you don't set ARGV[2] to null after reading it then awks going to try to open `accdias` like an input file, see https://stackoverflow.com/q/19075671/1745001. Also if you don't put a space after the `-v` (i.e. `-v a="$k"`) then it makes the script unnecessarily gawk-only. – Ed Morton Nov 27 '19 at 21:04
  • 1
    @EdMorton, you're absolutely right on all those (as always!). Thanks for the heads up and, if you don't mind, could you please fix the answer? I don't know how to do it. :-) – accdias Nov 27 '19 at 21:36
  • Thanks, Ed! That will sure help the OP. – accdias Nov 28 '19 at 01:57