【问题标题】:Renaming files with perl使用 perl 重命名文件
【发布时间】:2015-11-14 03:22:37
【问题描述】:

我是 perl 的新手,我想重命名一组文件,以便它们是小写而不是大写(所以从 SBC005.wav -> sbc005.wav)。

use strict;
use warnings;

my $dirnam = "/Users/.../SoundFiles";

opendir(DIR, $dirnam) or die "Cannot open directory: $!";
my @files = readdir(DIR);

foreach my $oldfile (@files) {
    my $newfile = lc($oldfile);
    #print $newfile;
    #print $oldfile;
    rename $oldfile, $newfile or die "Cannot rename file: $!";
    }

closedir(DIR);

我检查了变量是否与注释掉的打印语句一起正常工作,但是当我运行程序时,我收到一条消息,上面写着“无法重命名文件:rename.pl 第 13 行的参数无效”。我不确定我在这里做错了什么。

非常感谢!

编辑:

非常感谢楼下的回答!我发现使用glob 的这段代码也可以,但是下面的代码效果更好,因为它不必与声音文件位于同一目录中(就像glob 代码那样)

use strict;
use warnings;

my @files = glob("*.wav");

foreach my $oldfile (@files) {
    my $newfile = lc($oldfile);
    #print $newfile;
    #print $oldfile;
    rename $oldfile, $newfile or die "Cannot rename file: $!";
    }

exit 0;

【问题讨论】:

    标签: perl


    【解决方案1】:

    试试这个。重命名时忘记添加目录路径。

    use strict;
    use warnings;
    
    my $dirnam = "/Users/.../SoundFiles";
    
    opendir(DIR, $dirnam) or die "Cannot open directory: $!";
    my @files = readdir(DIR);
    
    foreach my $oldfile (@files) 
    {
        unless($oldfile  eq "." || $oldfile eq ".." )
        {           
    
            my $newfile = lc($oldfile);
    
            rename "$dirnam/$oldfile", "$dirnam/$newfile" or die "Cannot rename file: $!";
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 2016-08-17
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 2023-01-24
      • 2012-01-17
      相关资源
      最近更新 更多