曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3071|回复: 0
打印 上一主题 下一主题

rename -- 重命名文件

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2011-10-11 21:32:58 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
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
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-19 04:58 , Processed in 0.076927 second(s), 23 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表