【问题标题】:Perl regex with capture groups not working带有捕获组的 Perl 正则表达式不起作用
【发布时间】:2022-08-21 00:30:28
【问题描述】:

我有以下文件:

/Users/x/-acite _1660475490N.html
/Users/x/-acite _1660464772N.html
/Users/x/-acite _1660464242N.html
/Users/x/-acite _1660463321N.html
/Users/x/-acite _1660421444N.html
/Users/x/-acite _1612414441N.html

/Users/x/fix _1660399672N.html
/Users/x/fix _1660398829N.html

/Users/x/water witching _1660460617N.html
/Users/x/water witching _1660388149N.html
/Users/x/water witching _1632222441N.html
/Users/x/water witching _1660003224N.html

我需要

/Users/x/-acite _1660475490N.html
/Users/x/fix _1660399672N.html
/Users/x/water witching _1660460617N.html

我使用以下 perl 正则表达式:

find . -type f -exec perl -pi -w -e \'s/(.*)(\\R)(.*)(\\R)/$1$2/\' \\{\\} \\;

或者

find . -type f -exec perl -pi -w -e \'s/(.*?)(\\R)(.*?)(\\R)/$1$2/g;\' \\{\\} \\;

为什么这些不起作用?

    标签: regex perl


    【解决方案1】:

    此外,您可以在paragraph 模式下阅读 (-00),然后匹配并打印每个“段落”的第一行。

    C:\Old_Data\perlp>perl -00 -ne "print /(.+\n)/" test01.txt
    /Users/x/-acite _1660475490N.html
    /Users/x/fix _1660399672N.html
    /Users/x/water witching _1660460617N.html
    

    请注意,这是在 PC 上运行并在语句中使用双引号 (")。在 *nix 机器上,将使用单引号 (')。

    【讨论】:

      【解决方案2】:

      你是

      • 不将整个文件转换为单个字符串,并且
      • 只替换第一个匹配项
      • 你不需要这么多组,你只需要一个,因为你想保留一个匹配的一部分。

      你需要

      find . -type f -exec perl -0777 -i -pe 's/^(.+)(?:\R.+)*\n/$1/gm' \{\} \;
      

      这里,

      • -0777 啜饮文件
      • ^ - 一行的开始(由于 m 标志)
      • (.+) - 匹配非空行
      • (?:\R.+)* - 零个或多个换行符和非空行序列
      • \n - 匹配换行符

      【讨论】:

      • 我懂了。如果有不止一行,例如,怎么办? -acite 还是 water witching? (见上面的编辑)
      • @simoneante那么,您只需要保留第一个吗?
      • 正确的。只是第一个。
      猜你喜欢
      • 2021-09-06
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-20
      相关资源
      最近更新 更多