如果这是您第一次阅读本问题,请跳转到编辑
所以我想要做的就是匹配所有内容直到某个单词 我与之合作的内容与此相似:
{"selling":"0"morestuffhere"notes":"otherthingshere"}unwantedthingshere
到目前为止我得到的正则表达式是:
grep -o "\{\"selling\":\"0\""
最多匹配{"selling":"0"
。
我希望它与{"selling":"0"morestuffhere"notes":"otherthingshere"}
匹配,但不是unwantedstuffhere
。
我事先并不知道" morestuffhere","其他地方"和#34; unwantedherehere"会的。所以我想做的就是匹配我已经拥有的所有东西,直到"notes":"otherthingshere"}
。
我该怎么做?
编辑:忘了提一些关键点。对不起,不得不快点,因为晚餐准备好了。我的输入包含一系列键:值集,如下:
{"key":"value", "otherkey":"othervalue","morekeys":"morevalues"},{"othersetkey":"othersetvalue","otherothersetkey":"otherothersetvalue","othersetmorekeys":"othersetmorevalues"}
等等。
第一个键/值集与其他键/值集不同,我不想匹配该集。
除了第一个以外的所有集合中的第一个键是"selling"
,我希望匹配所有具有"销售"的集合。值1.该集的最后一个键是"notes"
。
输入是JSON,所以我将其添加到标签中。
答案 0 :(得分:2)
通过sed,
sed -r 's/^[^{]*([^}]*).*$/\1}/g' file
示例:
$ echo 'dSDGAadb{"selling":"0"morestuffhere"notes":"otherthingshere"}unwantedthingshere' | sed -r 's/^[^{]*([^}]*).*$/\1}/g'
{"selling":"0"morestuffhere"notes":"otherthingshere"}
我想你想要这样的东西,
$ cat aa
dSDGAadb{"selling":"0"morestuffhere"notes":"otherthingshere"}{"selling":"1"morestuffhere"notes":"otherthingshere"}bgj
$ sed -r 's/.*(\{"selling":"1"[^}]*)}.*/\1}/g' aa
{"selling":"1"morestuffhere"notes":"otherthingshere"}
OR
这样的事,
$ cat aa
dSDGAadb{"selling":"0"morestuffhere"notes":"otherthingshere"}{"selling":"1"morestuffhere"notes":"otherthingshere"}bgj{"selling":"1"morestuffhere"notes":"otherthingshere"}
$ grep -oP '{\"selling\":\"1\"[^}]*}' aa
{"selling":"1"morestuffhere"notes":"otherthingshere"}
{"selling":"1"morestuffhere"notes":"otherthingshere"}
答案 1 :(得分:1)
您可以使用grep
执行此操作:
grep -o '{[^}]*}' file
这匹配一个开口大括号,后跟任何不是右手大括号的东西,后面跟一个大括号。
在输入上测试它:
$ grep -o '{[^}]*}' <<<'{"selling":"0"morestuffhere"notes":"otherthingshere"}unwantedthingshere'
{"selling":"0"morestuffhere"notes":"otherthingshere"}
答案 2 :(得分:0)
有什么问题
>> grep -o ".*}" file.txt
{"selling":"0"morestuffhere"notes":"otherthingshere"}
其中file.txt
包含您的示例字符串?
答案 3 :(得分:0)
我从未找到过使用基本的unix工具(如grep,sed等)在shell中使用json做这种事情的好方法。快速而又脏的ruby或python脚本是你的朋友,
#!/usr/bin/env ruby
# h.rb
require 'json'
key=ARGV.shift
json=ARGF.read
h=JSON.parse(json)
puts h.key?(key) ? h[key] : "not found"
然后将json传输到脚本中,并将键指定为参数
$ echo '{"key":"value", "otherkey":"othervalue","morekeys":"morevalues"}' | /tmp/h.rb otherkey
othervalue
或来自文件,
$ cat /tmp/h.json | /tmp/h.rb otherkey
othervalue