Parse a string using keywords

Strip off the Location: and you're left with JSON:

$ echo '{"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' |
    jq .longitude
"133.453"

See in the man page if gps has an option to not print the Location: keyword up front, if not stripping it is easy, e.g.:

$ echo 'Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' |
    cut -d':' -f2- | jq .longitude
"133.453"

or:

$ echo 'Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' |
    sed 's/Location://' | jq .longitude
"133.453"

Unfortunately I don't have enough reputation to leave comments, but to expand upon Ed Morton's answer: if you call jq with the -r option, it will automatically strip quotes when the output is just a string (as it is in your case):

$ echo 'Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' | cut -d':' -f2- | jq -r .longitude
133.453

If you want to try this without jq (e.g. because it is unavailable), and the output is always a one-liner as implied by your example, the following sed approach would also work:

sed -r 's/.*"longitude": "([^"]+)".*/\1/'

This will

  • look for a string enclosed in double-quotes ( "([^"]+)", i.e. starting " followed by a string containing "anything but "" until the closing "), where the enclosed content is defined as "capture group" ( ... ), that occurs immediately after a string "longitude":
  • and replace basically the entire line with the content of the capture group (\1) - in your case, the actual value of the longitude

Test:

~$ echo 'Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}' | sed -r 's/.*"longitude": "([^"]+)".*/\1/'
133.453

Tags:

Bash

Awk

Sed

Cut