【问题标题】:How can I express this regex with sed?如何用 sed 表达这个正则表达式?
【发布时间】:2021-05-21 08:10:50
【问题描述】:

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

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

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

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

我正在考虑将字符类 [[:space:]][[:alnum:]] 结合起来,但没有奏效。

【问题讨论】:

  • 我收到一条错误消息,指出 z 是非法选项。这在 Mac 上不起作用吗?
  • 所以,你有一个 FreeBSD sed,试试sed -e '1h;2,$H;$!d;g' -e 's/"some_string":"ab.*"other_string_/"some_string":"removed text"other_string_/g' file。在other_string_ 之后的同一行 上是否还有其他文字?
  • 不错。我怎样才能做到这一点?
  • 试试:perl -i -0777 's/(?s)("some_string":)"ab.+"(other_string_)/$1"removed text"$2/g' file

标签: regex macos sed freebsd


【解决方案1】:

在 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 文本.

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

顺便说一句,如果你决定使用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_

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多