0

I am new to Awk and linux. I want to print 3rd column if 2nd column matches with a variable.

file.txt
1;XYZ;123
2;ABC;987
3;ZZZ;999

So I want to print 987, After checking if 2nd column is ABC

name="ABC"
awk -F';' '$2==$name { print $3 }' file.txt

But this is not working. Please help. Please note, I want to use AWK only, to understand how this can be achieved using awk.

  • 2
    Possible duplicate of [How do I use shell variables in an awk script?](https://stackoverflow.com/questions/19075671/how-do-i-use-shell-variables-in-an-awk-script) – Inian Jun 26 '18 at 09:56

1 Answers1

0

Do following and it should fly then. In awk variables don't work like shell you have to explicitly mention them by using -v var_name in awk code.

name="ABC"
awk -F';' -v name="$name" '$2==name{ print $3 }' file.txt
RavinderSingh13
  • 130,504
  • 14
  • 57
  • 93
  • DOWN VOTER, please do let me know reason for down vote? – RavinderSingh13 Jun 26 '18 at 09:56
  • 1
    I did and it was for answering a known duplicate that has been asked a billion times – Inian Jun 26 '18 at 09:57
  • 1
    It might have been posted billions of times, But i tried didn't find and simple answer here. May be because am brand new to awk, I was not able to relates existing questions. Thankyou @RavinderSingh13, it worked. – user3082166 Jun 26 '18 at 10:04
  • 1
    A simple google search on 'How to pass shell variable to awk' would have sufficed – Inian Jun 26 '18 at 10:05
  • 1
    Yup but before that one needs to know that variables works differently in awk. isn'it? or this platform is just for experts? – user3082166 Jun 26 '18 at 10:50
  • @user3082166, learning platform is open for everyone, keep learning and keep enjoying. – RavinderSingh13 Jun 26 '18 at 11:15
  • 1
    @user3082166: If you feel you are new to the site - Do read through [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) to know how the site works – Inian Jun 26 '18 at 11:24
  • @user3082166, I would like to advice you, keep learning, keep sharing and keep posting on site(Q & A) as we all are here to learn, cheers. – RavinderSingh13 Jun 26 '18 at 11:35