【问题标题】:Perl from command line: substitute regex only once in a file命令行中的 Perl:仅在文件中替换正则表达式一次
【发布时间】:2013-11-30 23:54:50
【问题描述】:

我正在尝试替换配置文件中的一行。问题是我只想替换一个事件。文件的一部分看起来像这样。它是 gitolite 默认配置文件:

# -----------------------------------------------------------------

# suggested locations for site-local gitolite code (see cust.html)

    # this one is managed directly on the server
    # LOCAL_CODE                =>  "$ENV{HOME}/local",

    # or you can use this, which lets you put everything in a subdirectory
    # called "local" in your gitolite-admin repo.  For a SECURITY WARNING
    # on this, see http://gitolite.com/gitolite/cust.html#pushcode
    # LOCAL_CODE                =>  "$rc{GL_ADMIN_BASE}/local",

# ------------------------------------------------------------------

我想从命令行将LOCAL_CODE 设置为其他值。我想我可能会在 perl 中这样做以获得 pcre 的便利。虽然我是 perl 新手,但无法让它工作。

我发现了这个:

perl -i.bak -p -e’s/old/new/’ filename

问题是 -p 似乎让它逐行遍历文件,因此'o'修饰符不会有任何效果。但是,如果没有 -p 选项,它似乎不起作用...

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    一个紧凑的方法是

    perl -i -pe '$done ||= s/old/new/' filename
    

    【讨论】:

      【解决方案2】:

      又一个单行:

       perl -i.bak -p -e '$i = s/old/new/ if !$i' filename
      

      【讨论】:

        【解决方案3】:

        可能有大量的 perl one 衬垫可以做到这一点,但这里有一个。

        perl -i.bak -p -e '$x++ if $x==0 && s/old/new/;' filename
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-09-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-08-28
          相关资源
          最近更新 更多