【问题标题】:Grep: invalid repetition countGrep:无效的重复计数
【发布时间】:2014-04-09 23:21:40
【问题描述】:

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

我的示例文本:

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

【问题讨论】:

  • 您是否考虑过使用json工具,或者xml api和xml工具?
  • 尽量保持轻量级——我不知道有任何此类用于 Bash 的工具
  • 如果其他人想知道,jq 是一个很棒的 CLI JSON 工具。

标签: regex bash shell curl grep


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2013-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 2020-07-18
    • 1970-01-01
    • 2015-12-18
    • 2012-10-13
    相关资源
    最近更新 更多