1

I have following variable set in my unix environment. If i try to use it in awk command its not working but the same command is working when i dont use $b variable

$b="NEW"

when i try following command it is not working

 echo "$a" | tr [a-z] [A-Z]  |awk -v RS=, '/TABLE/&&/CREATE/&&/`echo ${b}`/{print $NF}'

But, if i replace the $b value to NEW as below its working

 echo "$a" | tr [a-z] [A-Z]  |awk -v RS=, '/TABLE/&&/CREATE/&&/NEW/{print $NF}'
0

2 Answers 2

5

You cannot use a bash var inside awk like that. Instead, use:

echo "$a" | tr [a-z] [A-Z] | awk -v RS=, -v myvar=$b '/TABLE/&&/CREATE/&& $0~myvar {print $NF}'

See an example:

$ var="hello"
$ awk -v text=$var 'BEGIN{print text}'
hello

Also, to me it works with tr 'a-z' 'A-Z' instead of tr [a-z] [A-Z]. And based on Mark Setchell suggestion, you can skip it by using the IGNORECASE = 1:

echo "$a" | awk -v RS=, -v myvar=$b 'BEGIN{IGNORECASE=1} /TABLE/&&/CREATE/&& $0~myvar {print $NF}'
Sign up to request clarification or add additional context in comments.

10 Comments

Agreed, regarding the tr, In fact, it may be more elegant to set IGNORECASE=1 in the awk script.
That's a really good point, @MarkSetchell If you don't mind I will add it to my answer, for completeness. Thanks!
@fedorqui : if the $b has '_' its not working
@logan please update your question with sample input and desired output. Otherwise we are so abstract to give real answers.
@logan you did not ask for that in the beginning. Instead of asking more questions in comments, also repeating them in every answer, do Ask a new question. It will be more clear what you want and people will appreciate not having to update the answer over and over again.
|
1

Regarding your question:

if i replace the $b value to NEW as below its working

It works because the value of your variable is NEW and what you end up doing is using that in the regex, which is exactly how it is supposed to be done.

about your second question:

can not use unix $variable in awk command

You cannot use shell variables in awk like that. You need to create an awk variable by using -v option and assigning your bash variable.

awk -v awkvar="$bashvar" '/ /{ ... }'

This makes your existing syntax as:

echo "$a" | tr [a-z] [A-Z]  | awk -v RS=, -v var="$b" '/TABLE/&&/CREATE/&&/var/{print $NF}'

This again won't work because inside /../ variables are not interpolated, meaning they are considered literally. So, you need to do:

echo "$a" | tr [a-z] [A-Z]  |awk -v RS=, -v var="$b" '/TABLE/&&/CREATE/&&$0~var{print $NF}'

3 Comments

if the $b has '_' its not working
@logan Define not working? Error? No Output?
awk -v myvar=$b -F'$0~myvar' '{print $2}' is this correct method of using ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.