如何在 linux 中循环访问子目录并在 linux 上使用 perl 查找没有扩展名".csv"文件


#!/usr/bin/perl
my $dir = '/path/to/dir';
open( DIR, $dir ) or die $!;
while ( my $file = readdir(DIR) ) {
    next if ( $file =~ m/(^.)/ );
    if ( $file !~ m/csv$/ ) {
        print "*** renaming file $file ***n";
        $oldfile = $file;
        $file =~ s/..*$/.csv/;
        print "$oldfile => $filen";
        rename $oldfile, $file;
        print "Donen";
    }
}

我试着用perl-c来查看是否有语法错误。不知怎么的,我觉得我的逻辑有一个缺陷。感谢您提前提供的帮助。

有几个问题

  • 您正在使用open而不是opendir 读取目录

  • 您正在处理readdir返回的文件和目录

  • 您正在重命名没有路径的文件名,这意味着Perl将查找可能不是/path/to/dir 的当前目录

这将实现您想要的

use strict;
use warnings;
my $dir = '/path/to/dir';
chdir $dir or die $!;
opendir my $dh, '.' or die $!;
while ( my $file = readdir $dh ) {
    next unless -f $file;
    next if $file =~ /.csvz/i;
    print "*** Renaming file $file ***n";
    my $newfile = $file;
    $newfile =~ s/.[^.]*z//;
    $newfile .= '.csv';
    print "$file => $newfilen";
    rename $file, $newfile or die $!;
    print "Donen";
}

首先,open()用于文件。你想要的是opendir()。接下来,当您使用opendir(), readdir()时,它不会保留路径信息,因此您需要将其预先添加到要重命名的文件中。第三,与裸名相比,使用词法句柄更为常见。最后,始终使用use strict;use warnings;,它们会直接向您指出问题。

以下是您代码的略微更新版本:

#!/usr/bin/perl
use warnings;
use strict;
my $dir = "/path/to/dir";
opendir(my $dh, $dir) or die $!;
while ( my $file = readdir($dh) ) {
    next if ( $file =~ m/(^.)/ );
    next unless -f $file;
    if ( $file !~ m/csv$/ ) {
        print "*** renaming file $file ***n";
        my $oldfile = $file;
        $file =~ s/..*$/.csv/;
        print "$oldfile => $filen";
        rename "$dir/$oldfile", "$dir/$file";
        print "Donen";
    }
}

另一种方法是使用文件glob(根据Sobrique的建议(:

#!/usr/bin/perl
use warnings;
use strict;
my @files = </path/to/dir/*>;
for my $file (@files){
    next unless -f $file;
    if ($file !~ /.csv$/){
        print "*** renaming file $file ***n";
        my $oldfile = $file;
        $file =~ s/..*$/.csv/;
        print "$oldfile => $filen";
        rename $oldfile, $file;
        print "Done!n";
    }
}

最新更新