
因此,當從 Ookla 運行官方速度測試客戶端並輸出到 CSV 檔案時,我注意到輸出沒有時間戳字段。 JSON 可以,但我對 jq 不是特別了解,嘗試將 JSON 輸出轉換為 CSV 沒有用。
有沒有辦法獲取輸出並將其通過管道傳輸到前面帶有時間戳的文件?
這是以 JSON 形式給出的輸出
{"type":"result","timestamp":"2021-07-22T16:14:17Z","ping":{"jitter":0.035999999999999997,"latency":3.9399999999999999},"download":{"bandwidth":117078051,"bytes":884657048,"elapsed":7601},"upload":{"bandwidth":117029963,"bytes":467614102,"elapsed":4006},"packetLoss":0,"isp":"CenturyLink","interface":{"internalIp":"192.168.0.35","name":"eth0","macAddr":"E4:5F:01:2F:1D:39","isVpn":false,"externalIp":"71.214.44.165"},"server":{"id":10161,"name":"CenturyLink","location":"Orlando, FL","country":"United States","host":"orlando.speedtest.centurylink.net","port":8080,"ip":"205.171.98.14"},"result":{"id":"64657421-d008-4053-9832-2d1a9b01b649","url":"https://www.speedtest.net/result/c/64657421-d008-4053-9832-2d1a9b01b649"}}
這是 CSV 的輸出(有標題)
"server name","server id","latency","jitter","packet loss","download","upload","download bytes","upload bytes","share url"
"The Villages - The Villages, FL","25753","33.338","0.302","0","117318528","112406990","1488776432","1053747984","https://www.speedtest.net/result/c/8bbb92b8-880d-4021-b5e5-c90206862d18"
"CenturyLink - Orlando, FL","10161","4.013","0.399","0","76816660","112435444","1158108878","473391675","https://www.speedtest.net/result/c/17508892-6fc7-4616-84bb-810d314c50af"
"CenturyLink - Orlando, FL","10161","3.533","0.407","0","115293486","97552291","1002647576","574510787","https://www.speedtest.net/result/c/9913a846-1fbf-4d69-a1e9-27430914d397"
我想做的就是將 JSON 輸出的新增時間戳記資料轉換為 CSV 格式,以便我可以進一步處理。
答案1
這一行將會輸出你想要的內容:
<JSON> | jq -r '.timestamp, .server.name, .server.id, .pi ng.latency, .ping.jitter, .packetLoss, .download.bandwidth, .upload.bandwidth, .download.bytes, .upload.bytes, .result.url' | tr '\n' ',' | sed '$s/,$/\n/' | tee -a <CSV File>
使用您的範例 JSON,我提取了您想要的所有元素jq -r
:
.timestamp
.server.name
.server.id
.ping.latency
.ping.jitter
.packetLoss
.download.bandwidth
.upload.bandwidth
.download.bytes
.upload.bytes
.result.url
然後將結果通過管道傳送到tr `\n' ','
以形成逗號分隔的列表,然後tr
將結果通過管道傳送到sed '$s/,$/\n/'
以刪除結尾的逗號。
結果應該是這樣的:
2021-07-22T16:14:17Z,CenturyLink,10161,3.94,0.036,0,117078051,117029963,884657048,467614102,https://www.speedtest.net/result/c/64657421-d008-4053-9832-2d1a9b01b649
答案2
如果您嘗試直接運行 csv 文件,在做了一些我自己的研究之後,我做了以下操作:
#!/bin/sh
now=\"$(date +"%Y-%m-%d %H:%M:%S")\",
ookla -c http://www.speedtest.net/api/embed/vz0azjarf5enop8a/config -f csv | grep -v download | sed "s/^/$now/" >> /mnt/merlin/speedtest.csv
以最適合您的格式儲存日期。我還添加了引號和逗號以匹配生成的數據。稍後你會用到這個。
我運行 ookla 輸出來grep
刪除標題行,然後用於sed
插入我在行開頭創建的時間戳記。然後我將其附加到我的 csv 中。我在路由器上將其作為 cron 作業運行。希望這可以幫助。