Using awk with variables

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

does not print 3. How can I use variables with awk *

+6
source share
3 answers

Pass variables to awk using the -v flag.

 x=3 A=`echo $A|awk -vy=$x '{print y}'` echo $A 
+10
source

You can use shell variables this way: "'$your-shell-variable'" or '$your-shell-variable' . The first considers the variable as a string, and later considers it a number. Below is the code you want:

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

What is the echo point of $A ? It just creates a useless plug and pipe.

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

And while I'm in it, this seems like a confusing and expensive way to write A=$x

+1
source

Source: https://habr.com/ru/post/890685/


All Articles