【问题标题】:conditional grep from a Json file来自 Json 文件的条件 grep
【发布时间】:2021-08-17 09:29:53
【问题描述】:

我有一个关于这个 Json 和 grep 的查询:-

[
{
 "name":"Jon",
 "id":123
},
{
 "name":"Ray",
 "id":1234
},
{
 "name":"Abraham",
 "id":12345
}
]

如何使用 grep 或 sed 从这个 id 匹配的 json 中提取名称,比如 1234,可以是随机的?

【问题讨论】:

  • 你可以使用jqLink

标签: shell unix grep


【解决方案1】:

我建议使用jq,但如果你想使用 grep 试试

grep -B1 'id.*1234'  < input_file   |  grep name 

来自手册页

 -B num, --before-context=num
         Print num lines of leading context before each match.  See also the -A and -C options.

【讨论】:

  • 感谢 Digvijay,这将为我提供 Ray 和 Abrahm 的条目,因为它是包含条件。任何机会都可以将其细化为 Ray 另外,请建议 jq 命令
【解决方案2】:

请推荐 jq 命令

我冒昧地完成请求。

jq -r '.[]|select(.id==1234).name' file
  • .[] - 迭代数组元素
  • select(.id==1234) - 过滤具有所需 id 的元素
  • .name - 提取名称
  • -r 选项会导致名称不加引号。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多