6
x=3
A=`echo $A|awk '{print $x}'`
echo $A

doesnt print 3. How can i use variables with awk*

3 Answers 3

10

Pass variables to awk with the -v flag.

x=3
A=`echo $A|awk -v y=$x '{print y}'`
echo $A
Sign up to request clarification or add additional context in comments.

Comments

3

You can use the variables of shell by this way: "'$your-shell-variable'" or '$your-shell-variable'. The former considers the variable as string, while the later considers it as number. The following is the code you want:

x=3    
A=`echo $A|awk '{print "'$x'"}'`    
echo $A

Comments

2

Uh, what's the point of echoing $A? It just creates a useless fork and pipe.

x=3
A=`awk -v y=$x 'BEGIN {print y}'`
echo $A

And while I'm at it, this seems like a convoluted and expensive way to write A=$x :-)

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.