【问题标题】:search and print a string and value from a curl output从 curl 输出中搜索并打印字符串和值
【发布时间】:2014-06-04 15:03:42
【问题描述】:

我有一个 curl 命令,它返回单行但响应正文很长。并且需要搜索特定的字符串并打印结果。

例如,这里是 curl 的输出。我可以使用 bash 脚本来打印 centos 的“真”状态值吗?还是我应该使用不同的脚本/程序语言?该脚本应该基本上输出为 state=true。注意,输出中有两个“状态”值

~]# curl -v -k -u test:test https://myurl.com/api/state



"name":"centos","type":"disc","state":true},{"partitions":5},"auth_mechanisms":  [{"name":"PLAIN","description":"PLAIN authentication"}],   [{"name":"suse","type":"ram","state":true}]

【问题讨论】:

  • 对我来说它看起来像一个 JSON。也许可能需要像 jq 这样的 JSON 解析器?
  • 输出只是json?如果是这样,您可能想使用 python(真的很棒)library。这样你就可以使用所有的字典操作(我每天不经常使用 python,所以我想我可以轻松地说学习曲线还不错;我在 python 中写的一些第一件事就是使用这个)。
  • 值得注意的是json is a subset of yaml,所以如果你有一个也可以工作的yaml解析器。
  • 是的,只有json。
  • 感谢您的回复。看起来 python 脚本会更有效地完成这项任务。但是我是 Python 的新手,但会看到我能完成这个脚本有多接近。再次感谢!

标签: php bash unix curl


【解决方案1】:

你可以试试这个组合的sed 命令,

sed 's/},/\n/g' file | sed -nr '/centos/ s/.*:(.*)$/\1/p'

示例:

$ echo '"name":"centos","type":"disc","state":true},{"partitions":5},"auth_mechanisms":  [{"name":"PLAIN","description":"PLAIN authentication"}],   [{"name":"suse","type":"ram","state":true}]' | sed 's/},/\n/g' | sed -nr '/centos/ s/.*:(.*)$/\1/p'
true

【讨论】:

  • 非常感谢您的帮助。请告诉我如何提取名称及其各自的状态。例如,echo centos==true、suse==true。基本上,我的意图是对每个名称进行 grep 状态,并打印结果
猜你喜欢
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 1970-01-01
  • 2017-07-12
  • 2012-12-10
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多