Perl - 跨指定目录中的多个文件跨多行搜索和替换

时间:2014-02-06 15:19:06

标签: perl

目前,此代码替换了我的替换字符串中所有匹配字符串的出现,但仅用于我在命令行中指定的文件。有没有办法改变这一点,以便所有.txt文件,例如,在同一目录(我指定的目录)处理,而不必在单个文件上运行这100次?

#!/usr/bin/perl

use warnings;

my $filename = $ARGV[0];
open(INFILE,  "<",  $filename) or die "Cannot open $ARGV[0]";
my(@fcont) = <INFILE>;
close INFILE;

open(FOUT,">$filename") || die("Cannot Open File");
foreach $line (@fcont) {
 $line =~ s/\<br\/\>\n([[:space:]][[:space:]][[:space:]][[:space:]][A-Z])/\n$1/gm;
print FOUT $line;
 }
 close INFILE;

我也试过这个:

perl -p0007i -e 's/\<br\/\>\n([[:space:]][[:space:]][[:space:]][[:space:]][A-Z])/\n$1/m' *.txt

但是注意到只会改变匹配模式的第一次出现并忽略文件中的所有其余部分。

我也尝试了这个,但它只是创建一个空白文件的意义上不起作用:

use v5.14;
use strict;
use warnings;
use DBI;

my $source_dir = "C:/Testing2";

# Store the handle in a variable.
opendir my $dirh, $source_dir or die "Unable to open directory: $!";
my @files = grep /\.txt$/i, readdir $dirh;
closedir $dirh;

# Stop script if there aren't any files in the list
die "No files found in $source_dir" unless @files;

foreach my $file (@files) {
  say "Processing $source_dir/$file";
  open my $in, '<', "$source_dir/$file" or die "Unable to open $source_dir/$file: $!\n";
  open(FOUT,">$source_dir/$file") || die("Cannot Open File");

    foreach my $line (@files) {
        $line =~ s/\<br\/\>\n([[:space:]][[:space:]][[:space:]][[:space:]][A-Z])/\n$1/gm;
        print FOUT $line;
    }
    close $in;
}
say "Status: Processing of complete";

只是想知道我上面的代码中缺少什么?感谢。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法:

opendir(DIR,"your_directory");
my @all_files = readdir(DIR);
closedir(DIR);

for (@all_files) .....