Search code examples
awksedgrepgps

Trimming GPS information with awk


In a little bash script I simply try to trim GPS input data so that I have longitude and latitude values in separate variables:

  echo $geo_data
  GPS_latitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$2-1),1) $2}' )
  GPS_longitude=$( echo $geo_data | awk -F"+|-" '{print substr($0,index($0,$3-1),1) $3}' )
  echo $GPS_latitude
  echo $GPS_longitude

But what I get out seems to confuse the +/- signs in front of each component:

-04.7367+055.5230
-04.7367
-055.5230

I thought the index()-parameters would exactly avoid this situation, but obviously I did something wrong. Any idea how to fix this?


Solution

  • You need to subtract 1 from the output of index not the field value

    $ echo '-04.7367+055.5230' | awk -F"+|-" '{print substr($0,index($0,$2)-1,1) $2}' 
    -04.7367
    $ echo '-04.7367+055.5230' | awk -F"+|-" '{print substr($0,index($0,$3)-1,1) $3}' 
    +055.5230
    


    You can also use bash parameter expansion

    $ s='-04.7367+055.5230'
    $ a="${s%+*}"
    $ b="${s#${s%+*}}"
    $ echo "$a"
    -04.7367
    $ echo "$b"
    +055.5230
    
    $ # or, use the value of variable 'a'
    $ c="${s#$a}"
    $ echo "$c"
    +055.5230