简体   繁体   English

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

[英]Mac OS replace multiline with one character using sed

I hope this is not duplicate, I read some questions, but I am still struggling to achieve this.我希望这不是重复的,我读了一些问题,但我仍在努力实现这一目标。

Let say i have this text:假设我有这个文本:

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

How would I get the following result:我将如何得到以下结果:

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

I need to replace我需要更换

{
}

with just this就这个

,

Or better I need to replace this或者更好的是我需要更换这个

  }
}
{

with just this:就这样:

  },

What is the best way to achieve this using sed?使用 sed 实现此目的的最佳方法是什么?

I am not sure about the regex part, I tried this /^{}$/ and this $}^${^ .我不确定正则表达式部分,我试过这个/^{}$/和这个$}^${^

Thanks谢谢

With jq , it's just使用jq ,它只是

jq -s add tmp.json

The -s option reads both objects in the stream into a single array, then the add filter combines the two objects into one. -s选项将 stream 中的两个对象读取到一个数组中,然后add过滤器将两个对象合并为一个。

A demonstration:一个示范:

$ 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 can work but if you have the perl command you can also try: jq可以工作,但如果您有perl命令,您也可以尝试:

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

See argument docs请参阅参数文档

  • -0777 to read the whole file -0777读取整个文件
  • pe to evaluate what's in the quotes rather than a file, and loop it pe评估引号中的内容而不是文件,然后循环它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM