WX_M
WX_M

Reputation: 488

awk passing shell variables through awk commands

In an .xml file , I have some information:

 <var name="site1">
     <location lat="45.4558" lon="-98.4131" ht="422.0"/>
 </var>
 <var name="site2">
     <location lat="35.1497" lon="-106.8239" ht="1814.0"/>
 </var>
 <var name="site3">
     <location lat="36.9839" lon="-77.0075" ht="78.0"/>
 </var>

And I would like to extract the line after I search for 'sitex'. This is easily done with:

 awk '/site1/{getline;print}'

which, would correctly output:

 <location lat="45.4558" lon="-98.4131" ht="422.0">

Now if I want to get the lat information, I am able to do this with the complete line:

 awk '/site1/{getline;print}' | awk '{print $2}' | cut -d \" -f2

Which would produce 45.4558, correctly.

Now if I want to pass a variable into awk which can be done with the '-v' command, I have something that looks like below:

 locc="site1"
 awk -v var="$locc" '/var/{getline;print}' | awk '{print $2}' | cut -d \" -f2

However, this produces nothing (i.e., no output). What might the issue be here? If I simply try:

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

I get site1 as output. Therefore, it is correctly loading in the string I pass, but not parsing through the information correctly.

Upvotes: 0

Views: 40

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133528

Could you please try following.

var="site1"
awk -v val="$var" 'index($0,val){found=1;next} found{print;found=""}' Input_file

To get only specific value try following.

awk -v val="$var" 'BEGIN{FS="[\"=]"}index($0,val){found=1;next} found{print $3;found=""}' Input_file

Output will be 45.4558 for above command.

Upvotes: 2

Related Questions