代码之家  ›  专栏  ›  技术社区  ›  Carsten

使用最近的搜索模式更改文本块

  •  1
  • Carsten  · 技术社区  · 10 月前

    我想搜索并替换一个文本块:

    • 按开始模式和结束模式查找
    • 复制&;通过更改结束模式粘贴找到的块。

    我试过了 perl -0777 -pe 's/(section:[\s\S]*?"MARKER")/\$1 =~ s/"MARKER"/"NEW MARKER"/gr/e' input.txt (我知道,它没有按预期工作)

    对答案感到好奇:-)

    我的文本文件是这样的:

    Some content ...
      - section:
        this is some text
        this is some more text
        value: "MARKER"
      - another section:
        this is some text
        this is some more text
        value: "M7"
      - section:
        this is some text
        this is some more text
        value: "MARKER"
    ... content goes on
    

    我想搜索一个街区,在哪里

    • 以“-section:”开头
    • “-section:”后面跟着“value:”MARKER“”

    发现的块应为副本和;其背后贴着“MARKER”,被“NEW MARKER“取代。

    结果如下:

    Some content ...
      - section:
        this is some text
        this is some more text
        value: "MARKER"
      - section:
        this is some text
        this is some more text
        value: "NEW MARKER"
      - another section:
        this is some text
        this is some more text
        value: "M7"
      - section:
        this is some text
        this is some more text
        value: "MARKER"
      - section:
        this is some text
        this is some more text
        value: "NEW MARKER"
    ... content goes on
    
    2 回复  |  直到 10 月前
        1
  •  2
  •   jhnc    10 月前

    您的代码是:

    perl -0777 -pe 's/(section:[\s\S]*?"MARKER")/\$1 =~ s/"MARKER"/"NEW MARKER"/gr/e' input.txt
    

    这似乎是在尝试嵌套替换。

    /e 标志,RHS是实际代码,所以 $ 不应逃避:

    perl -0777 -pe 's/(section:[\s\S]*?"MARKER")/$1 =~ s/"MARKER"/"NEW MARKER"/gr/e' input.txt
    

    相反,嵌套的分隔符 s/// 必须 逃脱(或不同):

    perl -0777 -pe 's/(section:[\s\S]*?"MARKER")/$1 =~ s\/"MARKER"\/"NEW MARKER"\/gr/e' input.txt
    

    然而,这将“第…节营销人员”替换为“新营销人员”,这似乎不是人们想要的。


    相反,直接使用捕获组更简单:

    perl -0777 -pe 's/(section:[\s\S]*?)"MARKER"/$1"NEW MARKER"/g' input.txt
    

    或使用环视:

    perl -0777 -pe 's/section:[\s\S]*?\K"MARKER"/"NEW MARKER"/g' input.txt
    
        2
  •  0
  •   Carsten    10 月前

    非常感谢您提供示例和解释! 最后,我将这样使用它:

    perl -0777 -pe 's/(- section:[\s\S]*?)"MARKER"/$1"MARKER"\n$1"NEW MARKER 2"\n$1"NEW MARKER 3"/g' input.txt
    

    我的目标是找到第一个块,并用不同的块复制它 value: "MARKER" .

    太好了!

    最终结果:

    Some content ...
    - section:
    this is some text
    this is some more text
    value: "MARKER"
    - section:
    this is some text
    this is some more text
    value: "NEW MARKER 2"
    - section:
    this is some text
    this is some more text
    value: "NEW MARKER 3"
    - another section:
    this is some text
    this is some more text
    value: "M7"
    - section:
    this is some text
    this is some more text
    value: "MARKER"
    - section:
    this is some text
    this is some more text
    value: "NEW MARKER 2"
    - section:
    this is some text
    this is some more text
    value: "NEW MARKER 3"
    ... content goes on