首页 > 解决方案 > 两个值之间的Grep字符串Unix

问题描述

我有一个json数据如下。需要 grep 值并将其导出到新文件中。

{
"Data":
[
"User": [
      {"Name": "Solomon", "Age":20}, 
      {"Name": "Absolom", "Age":30}, 
   ] 
"Country": [
       {"Name" : "US", "Resident" : "Permanent"},
       {"Name" : "UK", "Resident" : "Temporary"}
]]}

预期结果,

需要grep“用户”的值并将其导出到新文件User.json

用户.json

"User": [
        {"Name": "Solomon", "Age":20}, 
        {"Name": "Absolom", "Age":30}, 
   ]

再次需要 grep "Country" 并导出到 Country.json

国家.json

"Country": [
       {"Name" : "US", "Resident" : "Permanent"},
       {"Name" : "UK", "Resident" : "Temporary"}
]

正在尝试sed,但得到的结果不正确

sed -e 's/.*"User"\(.*\)].*/\1/' Data.json > Users.json

由于有很多特殊字符]/[/{/},因此不确定如何正确 grep 值并将其导出到新文件。

任何建议都会非常有帮助

标签: unixawksedgrep

解决方案


运气好的话,您可以使用带有-z选项的 GNU sed 并过滤内容直到关闭],假设]字符串中没有:

sed -z 's/.*\("User":[^]]*]\).*/\1\n/'
sed -z 's/.*\("Country":[^]]*]\).*/\1\n/'

推荐阅读