0

The variable in awk does not return the result.

I am trying to get the next line of the matched value from file by using awk. It works fine without the variable. Thanks.

$ cat file
name=bobk
snm=sahh
emp=bklc
jdate=879
$
$ awk '/name/{getline; print}' file
snm=sahh   ---------> Got the result
$
$ export MYVAR=name
$
$ echo $MYVAR
name
$
$  awk -v AVAR=${MYVAR} '/AVAR/{getline; print}' file
$   ---------> No result

2 Answers 2

4

You need to use the regexp match operator ~ against the whole line $0 as /AVAR/ is match for the string AVAR not the variable AVAR:

$ awk -v AVAR=${MYVAR} '$0~AVAR{getline; print}' file
snm=sahh
Sign up to request clarification or add additional context in comments.

Comments

0

Using AWK variables to pass parameters is almost always cleaner as to intent; however, in this specific case, the resulting script is a bit more complex than it needs to be -- and breaking the rules a bit may actually be easier to understand and communicate to others.

With use of double-quotes to escape the script there is no need to use an additional AWK variable. That, and if we place the shell variable within /'s there is no need for the {}:

$ awk "/$MYVAR/ {getline; print}" file
snm=sahh
$

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.