首页 > 解决方案 > 打印文件中匹配模式的所有实例

问题描述

我一直在尝试从文件中打印匹配模式的所有实例。

输入文件:

{"id":"prod123","a":1.3,"c":"xyz","q":2}, 
{"id":"prod456","a":1.3,"c":"xyz","q":1}]}
{"id":"prod789","a":1.3,"currency":"xyz","q":2}, 
{"id":"prod101112","a":1.3,"c":"xyz","q":1}]}

我想打印 和 之间的所有"id":"内容",

预期输出:

prod123
prod456
prod789
prod101112

我正在使用命令

grep -Eo 'id\"\:\"[^"]+"\"\,*' | grep -Eo '^[^"]+'

我在这里错过了什么吗?

标签: bashawksedgrep

解决方案


出了问题的是第一个逗号的位置grep

grep -Eo 'id.\:.[^"]+"\,"' inputfile

您需要做一些额外的事情来获得所需的子字符串。

grep -Eo 'id.\:.[^"]+"\,"' inputfile | cut -d: -f2 | grep -Eo '[^",]+'

我使用cut, 这对于您的示例输入很容易。

cut -d'"' -f4 < inputfile

您有其他选择,例如使用jq, 或

sed -r 's/\{"id":"([^"]*).*/\1/' inputfile

或使用 awk (解决方案现在喜欢cut但可以轻松更改)

awk -F'"' '{print $4}' inputfile

推荐阅读