【问题标题】:sed command not select valuessed 命令不选择值
【发布时间】:2018-07-08 09:02:30
【问题描述】:

我需要 sed 命令的帮助。 我想通过选择 sed 来选择 json 值并分配给变量。 我该怎么做?

echo "{url:news.google.com,int:3}" | sed ?
url=news.google.com
int=3

【问题讨论】:

  • 避免将sed 用于json 输入...使用jq 之类的解析器或带有json 模块的编程语言..
  • 这真的是您要扫描的典型线条吗?

标签: json linux bash sed


【解决方案1】:

您能否尝试关注sed,如果这对您有帮助,请告诉我们:

url=$(echo "{url:news.google.com,int:3}" | sed 's/\({\)\([^:]*\)\(:\)\([^,]*\)\(.*\)/\4/')
echo "$url"
news.google.com


int=$(echo "{url:news.google.com,int:3}" | sed 's/.*://;s/}//')
echo "$int"
3

【讨论】:

    【解决方案2】:

    仅将sed 用于您可以完全控制的最简单的 JSON 结构。如果它变成任何嵌套的东西,sed 不是你想要的工具。正如 Sundeep 所说,jq、Perl、Python 等是更好的选择。

    话虽如此,

    echo "{url:news.google.com,int:3}" | sed 's/{//;s/}//;s/:/=/g;s/,/\n/g'
    

    将产生您的输出。

    【讨论】:

      【解决方案3】:

      使用 grep,虽然 grep 不是解析 json 的正确工具,但对于给定的数据,这应该可以工作

      grep -oP 'url:\K[^,}]*' 
      

      测试结果:

      $ echo "{url:news.google.com,int:3}" | grep -oP 'url:\K[^,}]*' 
      news.google.com
      
      $ echo "{url:news.google.com,int:3}" | grep -oP 'int:\K[^,}]*' 
      3
      
      • \K 用于重置之前匹配的数据

      要保存在变量中,请在$(...) 中将上面的一个包裹起来

      url=$( echo "{url:news.google.com,int:3}" | grep -oP 'url:\K[^,}]*' )
      

      $ url=$( grep -oP 'url:\K[^,}]*' <<<"{url:news.google.com,int:3}" )
      $ echo $url
      news.google.com
      

      【讨论】:

        猜你喜欢
        • 2012-09-22
        • 1970-01-01
        • 2021-06-17
        • 2021-11-30
        • 1970-01-01
        • 2014-11-05
        • 1970-01-01
        • 1970-01-01
        • 2014-09-16
        相关资源
        最近更新 更多