bash Grep:无效的重复计数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22239469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:49:25  来源:igfitidea点击:

Grep: invalid repetition count

regexbashshellcurlgrep

提问by jdotjdot

I'm very experienced with regex, but cannot figure out why this isn't working.

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

My sample text:

我的示例文本:

{
    "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
        }
    }
}

I'm trying to grab weather[0].id.

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

My full script (the curlgets the JSON):

我的完整脚本(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}'

I always get the error

我总是收到错误

grep: invalid repetition count(s)

回答by John1024

grep -edoes not recognize \das digits. It does not recognize non-greedy forms like .*?. For the grepportion of your command, try:

grep -e不能识别\d为数字。它不能识别像.*?. 对于grep您的命令部分,请尝试:

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

Alternatively, it your grepsupports it (GNU), use the -Poption for perl-like regex and your original regex will work:

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

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