2012-03-07 43 views
2

我正在玩一個bash腳本,解析cURL POST的輸出等。不是我的特長,而是一個有趣的項目。正則表達式匹配命令行中的多行

我的cURL的結果包含頭信息以及一個大json對象。我只想要json。這是輸出。 (我在github上創建了一個新的主題)

HTTP/1.1 201 Created 
Server: nginx/1.0.12 
Date: Wed, 07 Mar 2012 22:19:59 GMT 
Content-Type: application/json; charset=utf-8 
Connection: keep-alive 
Status: 201 Created 
X-RateLimit-Limit: 5000 
ETag: "8f778806263bd5c7b35a4d03f98663f7" 
Location: https://api.github.com/gists/1996642 
X-RateLimit-Remaining: 4989 
Content-Length: 1042 

{ 
    "html_url": "https://gist.github.com/1996642", 
    "files": { 
    "test.diff": { 
     "content": "this is content", 
     "type": "text/plain", 
     "raw_url": "https://gist.github.com/raw/1996642/434713954dc8d57f923dec99d82610828c5ef714/test.diff", 
     "language": "Diff", 
     "size": 15, 
     "filename": "test.diff" 
    } 
    }, 
    "git_pull_url": "git://gist.github.com/1996642.git", 
    "forks": [ 

    ], 
    "history": [ 
    { 
     "change_status": { 
     "additions": 1, 
     "deletions": 0, 
     "total": 1 
     }, 
     "user": null, 
     "url": "https://api.github.com/gists/1996642/2659edea4f102149b939558040ced8281ba8a505", 
     "version": "2659edea4f102149b939558040ced8281ba8a505", 
     "committed_at": "2012-03-07T22:19:59Z" 
    } 
    ], 
    "public": true, 
    "git_push_url": "[email protected]:1996642.git", 
    "comments": 0, 
    "updated_at": "2012-03-07T22:19:59Z", 
    "user": null, 
    "url": "https://api.github.com/gists/1996642", 
    "created_at": "2012-03-07T22:19:59Z", 
    "id": "1996642", 
    "description": null 
} 

我只想要這個json的一部分,並試圖用sed來做。以上內容存儲在一個名爲test.txt的文件中。

$ cat test.txt | sed 's/.*\({.*}\)/\1/' 

這是行不通的。所以,我的問題是如何使最後一個命令只顯示JSON對象。

回答

3

sed命令將完成這項工作,如果我明白什麼是JSON部分。從第一線

打印與{開始到文件結束:

sed -n '/^{/,$ p' test.txt 
+0

這樣做。謝謝! – hookedonwinter 2012-03-07 22:55:15

0

Perl有一個整潔的命令行開關是讓你在「段落」模式,而不是讀行由行。然後,你只需要跳過第一段:

perl -00 -ne 'print unless $. == 1' test.txt