Using awk with variables

2019-01-04 03:55发布

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

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

标签: shell awk
3条回答
乱世女痞
2楼-- · 2019-01-04 04:07

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 :-)

查看更多
ら.Afraid
3楼-- · 2019-01-04 04:29

Pass variables to awk with the -v flag.

x=3
A=`echo $A|awk -v y=$x '{print y}'`
echo $A
查看更多
SAY GOODBYE
4楼-- · 2019-01-04 04:29

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
查看更多
登录 后发表回答