对字符串和替换进行递归的Perl搜索文件

时间:2016-10-28 12:08:46

标签: perl

使用perl在终端中的

如何搜索从当前工作目录开始递归的所有php文件,用于单行或多行模式,如:

<script>var a=''; * hamoorabi.com * </script>

阅读如下:<script>var a='';</script>之间查找所有内容,但仅限于包含hamoorabi.com并将其替换为空字符串(将其删除)。

由于它是javascript代码,搜索字符串中可能会有一堆非转义字符。

3 个答案:

答案 0 :(得分:0)

从unix或cwygin提示符:

$ find . | grep .php | xargs ./xx1.pl

其中perl脚本xx1.pl是:

#!/usr/bin/perl

use strict;
use warnings;

undef $/;
for (@ARGV) {
        open(FILE,$_);
        my $content = <FILE>;
        close(FILE);
        my $beginning = '<script>var a=\'\'';
        my $end = '</script>';
        my $containing = 'hamoorabi.com';
        #$content =~ s/(<script>.*?)(hamoorabi.com)(.*?<\/script>)/$1$3/sg;
        #much better regex provided by ysth
        $content =~ s/\Q$beginning\E(?:(?!\Q$end\E).)*\Q$containing\E.*?\Q$end\E//gs;
        open(FILE,">$_");
        print FILE $content;
        close(FILE);
}

答案 1 :(得分:0)

使用File::Find遍历目录树查找文件。

use strict;
use warnings;
use File::Find;

sub wanted {
  # Ignore anything that isn't a file
  return unless -f;
  # Ignore anything without a .php extension
  return unless /\.php$/;

  # Your filename is in $_. Your current directory is the 
  # one which contains the current file.
  # Do what you need to do.
  open my $fh, '<', $_ or die $!;
  ...;
}

答案 2 :(得分:-1)

我希望这也有助于进一步使用。

use strict;
use warnings;
  

字符串替换Regex表单

my $str = "<script>var a=''\; * hamoorabi.com * </script>";
$str=~s#<script[^>]*>((?:(?!<\/script>).)*)<\/script># my $script=$&;
$script=~s/^(.*)hamoorabi\.com(.*)$/$1$2/g;
($script);
#esg;
print $str;
  

使用Tie::File

替换同一文件中的内容
my @array;
use Tie::File;
tie @array, 'Tie::File', "Input.php" || die "blabla";
my $len = join "\n", @array;
@array = split/\n/, $len;
untie @array;