rename 函数用来重命名文件。它的一般使用方法很简单:rename "old.file", "new.file"; 可以利用正则表达式进行批量改名,比如将当前目录下所有后缀名为 .txt 的文件全部修改为 .bak 后缀的:
# ls *.txt
test10.txt test1.txt test2.txt test3.txt test4.txt test5.txt test6.txt test7.txt test8.txt test9.txt 运行下面程序:
[Perl] 纯文本查看 复制代码 #!/usr/bin/perl
foreach my $file (glob "*.txt") {
my $newfile = $file;
$newfile =~ s/\.txt$/.bak/;
if (-e $newfile) {
warn "can't rename $file to $newfile: $newfile exists\n";
}elsif (rename $file, $newfile) {
#nothing to do, null
} else {
warn "rename $file to $newfile failed: $!\n";
}
}
查看结果:# ls *.bak
test10.bak test1.bak test2.bak test3.bak test4.bak test5.bak test6.bak test7.bak test8.bak test9.bak |