Mac OS 使用 sed 将多行替换为一个字符



我希望这不是重复的,我读了一些问题,但我仍在努力实现这一目标。

假设我有这段文字:

{
"root": {
"2020-05": []
}
}
{
"root2": {
"result": "error",
"message": "You can't access this resource as it requires 'view' access for the website id = 206."
}
}

我将如何获得以下结果:

{
"root": {
"2020-05": []
},
"root2": {
"result": "error",
"message": "You can't access this resource as it requires 'view' access for the website id = 206."
}
}

我需要更换

{
}

就这个

,

或者更好的是我需要替换这个

}
}
{

只有这个:

},

使用 sed 实现此目的的最佳方法是什么?

我不确定正则表达式部分,我尝试了这个/^{}$/和这个$}^${^.

谢谢

有了jq,它只是

jq -s add tmp.json

-s选项将流中的两个对象读取到单个数组中,然后add筛选器将两个对象合并为一个。

演示:

$ jq -s add <<EOF
> {
>   "root": {
>     "2020-05": []
>   }
> }
> {
>   "root2": {
>     "result": "error",
>     "message": "You can't access this resource as it requires 'view' access for the website id = 206."
>   }
> }
> EOF
{
"root": {
"2020-05": []
},
"root2": {
"result": "error",
"message": "You can't access this resource as it requires 'view' access for the website id = 206."
}
}

jq可以工作,但如果你有perl命令,你也可以尝试:

perl -0777 -pe 's/}n{/,/g' file.txt

查看参数文档

  • -0777读取整个文件
  • pe评估引号而不是文件中的内容,并循环它

最新更新