2014-03-07 25 views
5

我對於正則表達式非常有經驗,但無法弄清楚爲什麼這不起作用。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) 
+2

你有沒有考慮過使用json工具,或者使用xml api和xml工具? –

+0

試圖保持這個儘可能輕 - 我不知道有任何這樣的工具Bash – jdotjdot

+0

如果別人想知道,['jq'](https://stedolan.github.io/jq/)是一個偉大的CLI JSON工具。 – orlade

回答

9

grep -e不承認\d的數字。它不承認非貪婪的形式,如.*?。爲了您的命令grep部分,嘗試:

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

或者,您grep支持它(GNU),使用類似Perl的正則表達式的-P選項,你原來的正則表達式將工作:

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