我如何用 sed 表达这个正则表达式?

How can I express this regex with sed?

我有这个要与 sed 一起使用的正则表达式。我想使用 sed,因为我想批处理几千个文件,而我的编辑器不喜欢那样

查找:"some_string":"ab[\s\S\n]+"other_string_

替换:"some_string":"removed text"other_string_

Find 基本上匹配 some_string 和 other_string 之间的所有内容,包括特殊字符,如 , ; - 或 _ 并将其替换为文本已被删除的警告。

我正在考虑将字符 类 [[:space:]][[:alnum:]] 组合起来,但没有成功。

在 MacOS FreeBSD sed 中,您可以使用

sed -i '' -e '1h;2,$H;$!d;g' -e 's/"some_string":"ab.*"other_string_/"some_string":"removed text"other_string_/g' file

1h;2,$H;$!d;g 部分将整个文件读入内存,以便所有换行符都暴露给正则表达式,然后 "some_string":"ab.*"other_string_ 匹配来自 "some_string":"ab 的文本,直到最后一次出现 "other_string_ 并替换为 RHS 文本。

您需要在 FreeBSD sed 中使用 -i '' 来强制执行内联文件修改。

顺便说一句,如果你决定使用 perl,你真的可以使用 -0777 选项来启用带有 s 修饰符的文件 slurping(这使得 . 匹配任何字符,包括换行符)并使用类似

perl -i -0777 's/"some_string":"\Kab.*(?="other_string_)/removed text/gs' file

这里,

  • "some_string":" - 匹配文字文本
  • \K - 省略当前匹配内存缓冲区中到目前为止匹配的文本
  • ab - 匹配 ab
  • .* - 尽可能多的任意零个或多个字符
  • .*? - 任何零个或多个字符,尽可能
  • (?="other_string_) - 正向前瞻(与文本匹配但不附加到匹配值)确保右边有 "other_string_