Grep:重复计数无效

时间:2014-03-07 01:06:32

标签: regex bash shell curl grep

我对正则表达式非常有经验,但无法弄清楚为什么这不起作用。

我的示例文字:

{
    "coord":
    {
        "lon":-74.01,
        "lat":40.71
    },
    "sys":
    {
        "message":0.2452,
        "country":"United States of America",
        "sunrise":1394191161,
        "sunset":1394232864
    },
    "weather":
    [
        {
            "id":803,
            "main":"Clouds",
            "description":"broken clouds",
            "icon":"04n"
        }
    ],
    "base":"cmc stations",
    "main":
    {
        "temp":270.54,
        "pressure":1035,
        "humidity":53,
        "temp_min":270.15,
        "temp_max":271.15},
        "wind":
        {
            "speed":2.1,
            "deg":130},
            "clouds":
            {
                "all":75
            },
            "dt":1394149980,
            "id":5128581,
            "name":"New York",
            "cod":200
        }
    }
}

我正试图抓住weather[0].id

我的完整脚本(curl获取JSON):

curl -s "http://api.openweathermap.org/data/2.5/weather?q=NYC,NY" 2>/dev/null | grep -e '"weather":.*?\[.*?\{.*?"id": ?\d{1,3}'

我总是收到错误

grep: invalid repetition count(s)

1 个答案:

答案 0 :(得分:10)

grep -e无法将\d识别为数字。它不识别像.*?这样的非贪婪形式。对于命令的grep部分,请尝试:

grep -e '"weather":[^[]*\[[^{]*{[^}]*"id": *[0-9]\{1,3\}'

或者,你的grep支持它(GNU),使用-P选项为类似perl的正则表达式,你的原始正则表达式将起作用:

grep -P '"weather":.*?\[.*?\{.*?"id": ?\d{1,3}'