shell 使用sed从JSON中提取非贪婪正则表达式

2sbarzqh  于 2023-08-07  发布在  Shell
关注(0)|答案(1)|浏览(90)

一些JSON:

{"theSecret":"flhiusdh4543sdfasf34sdf+fsfs/sdf43454=","foo":{"bar":41,"something":"hello world","else":"hi","date":20230101,"qux":0,"digest":"sfhusdf234jkkjuiui23kjkj/SFDF34SDSFDS="}}

字符串
预处理:

{
  "theSecret": "flhiusdh4543sdfasf34sdf+fsfs/sdf43454=",
  "foo": {
    "bar": 41,
    "something": "hello world",
    "else": "hi",
    "date": 20230101,
    "qux": 0,
    "digest": "sfhusdf234jkkjuiui23kjkj/SFDF34SDSFDS="
  }
}


我想要theSecret键的值。
我试过这个:

$ echo "$json" | sed -nE 's/.*theSecret":"(.*)".*/\1/p'    # (.*?) doesn't work


其给出:

flhiusdh4543................4SDSFDS=


即从theSecret直到digest的结束。这是因为sed缺少非贪婪量词,所以.*?不起作用。
我该怎么办?
(This是在一个高山集装箱里,它有sedgrepawkjqperl不可用。)

mefy6pfw

mefy6pfw1#

不要使用非贪婪量词,而要使用不匹配终止符"的模式。

$ echo "$json" | sed -nE 's/.*theSecret":"([^"]*)".*/\1/p'    # (.*?) doesn't work

字符串

相关问题