Perl:以递归方式重命名所有文件和目录 [英] Perl: Recursively rename all files and directories

查看:94
本文介绍了Perl:以递归方式重命名所有文件和目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要递归地重命名每个文件和目录.我将空格转换为下划线,并将所有文件/目录名称转换为小写.如何使以下脚本一次运行即可重命名所有文件?当前,在转换所有文件/目录之前,该脚本需要运行几次.代码如下:

I need to recursively rename every file and directory. I convert spaces to underscores and make all file/directory names to lowercase. How can I make the following script rename all files in one run? Currently the script needs to be run several times before all the files/directories are converted. The code is below:

#!/usr/bin/perl

use File::Find;

$input_file_dir = $ARGV[0];

sub process_file {
        $clean_name=lc($_);
        $clean_name=~s/\s/_/g;
        rename($_,$clean_name);
        print "file/dir name: $clean_name\n";
}
find(\&process_file, $input_file_dir);

推荐答案

您需要在传递的选项中指定bydepth => 1来查找或调用finddepth.来自 perldoc File :: Find :

You either need to specify bydepth => 1 in the options you pass to find or call finddepth. From perldoc File::Find:

bydepth

仅在报告了所有目录条目之后,才报告目录的名称.入口点finddepth()是在find()的第一个参数中指定{ bydepth => 1 }的快捷方式.

Reports the name of a directory only AFTER all its entries have been reported. Entry point finddepth() is a shortcut for specifying { bydepth => 1 } in the first argument of find().

但是,您仍然需要决定如何处理命名冲突,因为如果目标存在,重命名会破坏目标..

#!/usr/bin/perl

use strict; use warnings;
use File::Find;

finddepth(\&process_file, $_) for @ARGV;

这篇关于Perl:以递归方式重命名所有文件和目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆