gpt4 book ai didi

regex - 我怎样才能用 sed 表达这个正则表达式?

转载 作者:行者123 更新时间:2023-12-04 08:05:00 25 4
gpt4 key购买 nike

我有这个正则表达式,我想与 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 part 将整个文件读入内存,以便所有换行符都暴露给正则表达式,然后 "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_立即在右侧。
  • 关于regex - 我怎样才能用 sed 表达这个正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66258871/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com