重命名文本文件

时间:2013-07-24 05:11:35

标签: regex perl

我在目录中有多个具有不同名称的文本文件。我想在所有文本文件中搜索一个字符串,如果在任何文本文件中找到该字符串,我想将该文本文件重命名为ABC.txt

任何人都可以帮我做这个perl脚本。

1 个答案:

答案 0 :(得分:2)

这应该做你想要的。

你应该花一些时间来弄清楚它是如何工作的。

“我想将该文本文件重命名为ABC.txt”

希望您知道在同一目录中只能有one名为ABC.txt的文件。所以我正在制作文件:ABC.txt ABD.txt ABE.txt等等......

这是未经测试的BTW ......

#!/usr/bin/perl

use strict; 
use warnings;

use autodie;
use File::Copy;

my $dir = "test-dir";
opendir(my $dh, $dir);
chdir $dir;

my @files = grep { !-d $_ } readdir $dh; 

closedir $dh;

my $new = "ABC";
for my $file (@files) {
    open my $fh, "<", $file;

    while(my $line = <$fh>) {
        chomp $line;
        if($line =~ /something/) {
            move($file, "$new.txt"); 
            $new++;
            last;
        }   
    }   
    close $fh;
}
相关问题