【问题标题】:How to remove a text block by regular expression with sed or perl or awk etc?如何使用 sed 或 perl 或 awk 等通过正则表达式删除文本块?
【发布时间】:2013-12-01 13:02:35
【问题描述】:

我有一个 php 文件:

<?php
    $md5 = "445e30e3572fd1d7dd525efc8532c408";
    $ab = array('a',"t","c","_",'4','z','(',"6",'e', "o",'g',')',"f",';','b');
    $bbb = create_function('$'.'v',$ab[8].$ab[12]...);
    $bbb('DZZF0oRqEkWX0...');
?>
<?php
    //SOME PHP CODE
?>

我想使用 perl/sed/awk 删除第一块代码(以 &lt;?php 开头和结尾)。

我尝试使用以下 PHP 正则表达式:

<\?php\n\$md5[\s\S]*?\?> 

但它不适用于 perl 和 sed。对于我做错了什么有什么建议吗?

【问题讨论】:

  • 你可能遇到的主要陷阱,因为它是 php 代码,是一个?> 在字符串中(quote、heredoc、nowdoc)。

标签: regex perl sed awk


【解决方案1】:
cat in.txt

<?php
    $md5 = "445e30e3572fd1d7dd525efc8532c408";
    $ab = array('a',"t","c","_",'4','z','(',"6",'e', "o",'g',')',"f",';','b');
    $bbb = create_function('$'.'v',$ab[8].$ab[12]...);
    $bbb('DZZF0oRqEkWX0...');
?>
<?php
    //SOME PHP CODE
?>

使用 sed:

sed '/<?php/,/<?php/d' in.txt

输出:

 //SOME PHP CODE
?>

【讨论】:

    【解决方案2】:

    这可能有帮助吗?

     awk '/^?>/{if(!f){f=1;next}}f' file
    

    输出:

    <?php
        //SOME PHP CODE
    ?>
    

    【讨论】:

      【解决方案3】:

      如果您想避免在引号内或在 heredoc/nowdoc 语法中使用虚伪的 ?&gt;,您可以使用这个(有点长)模式:

      #!/usr/bin/perl 
      use strict;
      use warnings;
      my $string = <<'END';
      <?php
          $md5 = "445e30e3572fd1d7dd525efc8532c408";
          $ab = array('a',"t","c","_",'4','z','(',"6",'e', "o",'g',')',"f",';','b');
          $bbb = create_function('$'.'v',$ab[8].$ab[12]...);
          $bbb('DZZF0oRqEkWX0...');
      ?>
      <?php
          //SOME PHP CODE
      ?>
      END
      
      my $pattern = qr/
          <\?php\s+\$md5
          (?> [^"'?<]++                         # all characters except " ' < ?
            | \?(?!>)                           # ? not followed by >
            | "(?>[^\\"]++|\\{2}|\\.)*"         # string inside double quotes
            | '(?>[^\\']++|\\{2}|\\.)*'         # string inside simple quotes
            | <(?!<<\'?\w)                      # < that is not the start of an heredoc declaration
            | <<<(\'?)(\w++)\1\R.*?(?<=\n)\2\R  # string inside heredoc or nowdoc
          )*
         \?>
       /xs;
      
      $string =~ s/$pattern//g; # for only the first occurence you can remove the g
      print $string;
      

      (对不起,它不是单行)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-07
        • 2018-07-01
        • 1970-01-01
        • 2019-02-16
        • 1970-01-01
        • 2014-07-09
        • 1970-01-01
        • 2012-04-10
        相关资源
        最近更新 更多