简体   繁体   English

bash脚本-grep json变量

[英]bash script - grep a json variable

I would like the simplest solution for my pretty basic bash script: 我想要最基本的bash脚本的最简单解决方案:

#!/bin/bash

    # Weather API url format: http://api.wunderground.com/api/{api_key}/conditions/q/CA/{location}.json
    # http://api.wunderground.com/api/5e8747237f05d669/conditions/q/CA/tbilisi.json

        api_key=5e8747237f05d669
        location=tbilisi
        temp=c

        api=$(wget -qO- http://api.wunderground.com/api/$api_key/conditions/q/CA/$location.json)
        temp_c=$api | grep temp_c
        temp_f=$api | grep temp_f

        if [ $temp = "f" ]; then
            echo $temp_f
        else
            echo $temp_c
        fi

grep returns empty. grep返回空。 This is my first bash script, I'm getting hold of syntax, so please point out obvious errors. 这是我的第一个bash脚本,我掌握语法,因此请指出明显的错误。

I also don't understand why I have $() for wget . 我也不明白为什么我要为wget使用$()。

You can use: 您可以使用:

temp_c=$(echo $api|awk '{print $2}' FS='temp_c":'|awk '{print $1}' FS=',')
temp_f=$(echo $api|awk '{print $2}' FS='temp_f":'|awk '{print $1}' FS=',')

Instead of: 代替:

temp_c=$api | grep temp_c
temp_f=$api | grep temp_f

I am getting following JSON response from curl and storing in variable : 我从curl获取以下JSON响应并将其存储在variable中:

CURL_OUTPUT='{ "url": "protocol://xyz.net/9999" , "other_key": "other_value" }'

Question :I want to read the url key value and extract the id from that url: 问题:我想读取URL键值并从该URL中提取ID:

Answer : _ID=$(echo $CURL_OUTPUT |awk '{print $2}' FS='url":' |awk '{print $1}' FS=',' | awk '{print $2}' FS='"'|awk '{print $4}' FS='/') 答案: _ID=$(echo $CURL_OUTPUT |awk '{print $2}' FS='url":' |awk '{print $1}' FS=',' | awk '{print $2}' FS='"'|awk '{print $4}' FS='/')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM