Bash

使用關鍵字解析字元串

  • July 17, 2020

我正在使用 bash 命令,gps location它返回日期、時間和位置資訊。

[john@hostname :~/develp] $ gps location
Location: {"date": "16/07/20", "time": "19:01:22", "latitude": "34.321", "longitude": "133.453", "altitude": "30m"}

我想將經度寫入文件,在到達那里之前我需要正確解析字元串。

[john@hostname :~/develp] $ variable=`gps location | awk '/"longitude":/ {print $9}'`
[john@hostname :~/develp] $ echo $variable
"133.453",
[john@hostname :~/develp] $

目前,awk不搜尋經度,它只是獲取整個字元串並找到第 9 個字元串。理想情況下,我想使用正則表達式/關鍵字方法並找到經度,然後找到下一個字元串。我試過使用grep | cut也試過了sed。不走運,我能做的最好的就是使用awk.

去掉Location:,你就剩下 JSON:

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

gps如果可以選擇不預先列印Location:關鍵字,請參見手冊頁,如果不剝離它很容易,例如:

$ 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"

或者:

$ 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"

引用自:https://unix.stackexchange.com/questions/598906