简体   繁体   English

重命名文件夹及其子文件夹的文件

[英]rename files of a folder and its folders children

I would like to add prefix on all files in a folder and in all files in all of folder children. 我想在文件夹中的所有文件以及所有子文件夹中的所有文件中添加前缀。

Exemple : 范例:

hello\file1
 hello2\file2
 file3
 file4

the result should be after adding the prefix PRE_ 结果应在添加前缀PRE_之后

hello\PRE_file1
 hello2\PRE_file2
 PRE_file3
 PRE_file4

i tried to do this : 我试图这样做:

find . -type f -exec rename 's/^/PRE_/' '{}' \\;

but it modify all the name. 但会修改所有名称。 Thank you 谢谢

Also you could use only perl if you want, without any additional modules: 另外,如果需要,您可以仅使用perl,而无需任何其他模块:

use strict;
use warnings;

my ($prefix, $dir) = ('PRE_', '/home');
sub loop_dirs {
    my $path = $_[0];
    if (-d $path) { # if directory
         opendir my $dh, $path or die "$!";
         loop_dirs($path.'/'.$_) for grep ! /^\.{1,2}$/, readdir $dh; close $dh;
    } elsif (-e $path) { # if file
         prefix_add($path, $prefix); # do smth with file, e.g. rename
    }
}
sub prefix_add { my ($path, $pref) = @_; $path =~ s/([^\/]+)$/$pref$1/; rename $_[0], $path }
loop_dirs($dir);

This code works well both on Windows(ActivePerl) and Linux 此代码在Windows(ActivePerl)和Linux上均能正常运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM