【问题标题】:perl command line one liner to do find/replace, but *not* print lines that don't match?perl 命令行 一个行来查找/替换,但 *not* 打印不匹配的行?
【发布时间】:2020-12-04 08:22:12
【问题描述】:

我想在命令行上使用复杂的正则表达式对文件进行正则表达式查找和替换,所以我需要 PCRE 并使用 perl -pe "s/foo/bar"(而不是 sed),在应用 @ 后打印出所有行987654323@,但它也会打印不匹配的行。

是否有perl 命令行单行器不会打印不匹配的行?我知道perl -pe s/foo/bar/ if /foo/,但是我需要复制正则表达式。不重复自己有可能吗?

【问题讨论】:

    标签: regex perl command-line one-liner


    【解决方案1】:

    @Dada 的回答显示了解决 OP 确切问题的最简洁方法。
    下面是一些其他等效但更长的方法来做同样的事情。它们的优点是,除了简单地打印这些行之外,这些单行代码还可以更容易地扩展以执行一些其他附加代码(如果需要)。

    perl -ne 'if ( s{foo}{bar} ) { print; }'
    # Same:
    perl -ne 'next LINE unless s{foo}{bar}; print;'
    

    这些可以扩展为:

    perl -ne 'if ( s{foo}{bar} ) { some(); other(); code(); print; }'
    # Same:
    perl -ne 'next LINE unless s{foo}{bar}; some(); other(); code(); print;'
    

    另请参阅:

    perlrun: command line switches
    What should every Perl hacker know about perl -ne?

    要查看各种用例中的这些命令行开关,包括一些出色的 Perl 单行代码,请参阅:
    What is your latest useful Perl one-liner (or a pipe involving Perl)?

    【讨论】:

      【解决方案2】:

      您可以使用-n flag(与-p 不同,它不会自动打印所有行)并仅打印与正则表达式匹配的行:

      perl -ne 's/foo/bar/ && print'
      

      或者,等效地:

      perl -ne 'print if s/foo/bar/'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-29
        • 1970-01-01
        • 1970-01-01
        • 2017-12-27
        • 2022-10-12
        • 2013-02-09
        • 1970-01-01
        相关资源
        最近更新 更多