Using awk with variables

感情迁移 提交于 2020-01-18 04:44:14

问题


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

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


回答1:


Pass variables to awk with the -v flag.

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



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/6373379/using-awk-with-variables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!