【问题标题】:regex match against multiple lines at the command line正则表达式匹配命令行中的多行
【发布时间】:2012-03-25 12:01:17
【问题描述】:

我正在使用 bash 脚本,解析 cURL POST 的输出等。这不是我的强项,而是一个有趣的项目。

我的 cURL 的结果包含标题信息以及一个大的 json 对象。我只想要json。这是输出。 (我正在 github 上创建一个新的 gist)

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": "git@gist.github.com: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 对象。

【问题讨论】:

    标签: regex command-line sed


    【解决方案1】:

    如果我正确理解JSON 部分是什么,这个sed 命令将完成这项工作。

    从第一行以{ 开始打印到文件结尾:

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

    【讨论】:

      【解决方案2】:

      Perl 有一个简洁的命令行开关,可以让您进入“段落”模式,而不是逐行阅读。然后,您只需要跳过第 1 段:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-23
        • 2017-07-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-11
        • 1970-01-01
        相关资源
        最近更新 更多