gpt4 book ai didi

linux - Perl:递归重命名所有文件和目录

转载 作者:IT王子 更新时间:2023-10-29 00:54:18 25 4
gpt4 key购买 nike

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

#!/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 :

bydepth

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;

关于linux - Perl:递归重命名所有文件和目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2557199/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com