json 使用捕获的大括号组用sed编辑(windows)

jjjwad0x  于 2022-12-15  发布在  Windows
关注(0)|答案(2)|浏览(84)

在Windows上,我尝试对格式错误的简单JSON文件进行就地编辑。我的文件看起来像这样,第一个对象重复。

{
  "hello":"there"
}
{
  "hello":"there"
}

我的目标是只拥有一个对象,并丢弃第二个对象。我应该注意到,文件有换行符,如下所示。

{
  "hello":"there"
}

我可以使用像^({.*?}).*这样的正则表达式匹配第一组,这相当简单。
看起来像是sed就地编辑的完美工作。但是显然无论我在sed中使用什么转义组合,我都无法匹配括号。我使用的是Michael M. Builov的(GNU sed) 4.9补丁。
我得到的一些结果:

# as per original regexp
sed.exe -E "s,^({.*?}).*,d,g" double.json
     ->  -e expression #1, char 16: Invalid preceding regular expression

# trying to escape paranthesis
sed.exe -E "s,^\({.*?}\).*,d,g" double.json
     ->  -e expression #1, char 18: Invalid content of \{\}

# escaping curly brackets
sed.exe -E "s,^\(\{.*?\}\).*,d,g" double.json
     -> Works, but original file is returned (no match)

这在Windows上完全可能吗?根据thisthis comment,Windows似乎出于某种原因不喜欢带sed的花括号。
注:在WSL/Ubuntu中测试,结果相同。

cl25kdpy

cl25kdpy1#

你可以试试这个GNU sed

$ sed -Ez 's/((\{[^}]*}).*)\2/\1/' input_file
{
  "hello":"there"
}
rqmkfv5c

rqmkfv5c2#

jq命令行工具对于JSON值非常方便,即使在Windows上也是如此。您可以通过this link下载作为示例。
然后保存命令

inputs

导入到名为double.jq的文件中,然后通过以下命令从命令行调用
[Windows键]+ cmd

cd to_the_path_where_the_files_reside    
jq -f double.jq <double.json

如果在文件double.json内存在多于两个的独立对象

{
  "hello":"there"
}
{
  "hello":"there"
}
{
  "hello":"there"
}
{
  "hello":"there"
}

并且只想选取第一个,则将double.jq的代码转换为

[inputs] | unique | .[]

相关问题