批量重命名以相反的顺序目录 [英] Batch rename directories in reverse order
问题描述
我有一堆(超过700),它们通过以下方式命名的目录
I have a bunch (more than 700) directories that are named in the following manner
1 - *random*name*1*
2 - *random*name*2*
...
725 - *random*name*725*
前置号码(1-725)是目录名的一部分。
The leading numbers (1-725) are all part of the directory names.
那就是:所有的目录名以数字开头,后跟[空格] [短跑] [空格],其次是一些文字
我想批量重命名他们,这样他们就会被命名为以下几点:
I'd like to batch rename them, so that they'll be named as following:
1 - *random*name*725*
2 - *random*name*724*
...
725 - *random*name*1*
我想反向只是目录名的数量部分。从本质上讲,我想以后来到文本1 - 遵循725 - ,之后来到文本2 - 按照724 - 等等
I'd like to "reverse" just the number parts of the directory names. Essentially I'd like the text that came after "1 - " to follow "725 - ", the text that came after "2 - " to follow "724 - " and so on.
什么是做到这一点的最简单的方法?我在Linux上。
What is the easiest way to do that? I'm on linux.
注意:的*随机* *名称都不同,而且只是为了演示
Note: The *random*names* are all different and are just for illustration purposes.
推荐答案
使用的一种方法 perl的
。 code被注释。
One way using perl
. Code is commented.
内容 script.pl
:
#!/usr/bin/env perl
use warnings;
use strict;
use File::Basename qw|basename|;
die qq{Usage: perl $0 <real|trial>\n} unless @ARGV == 1;
my $real = $ARGV[0] eq q|real| ? 1 : 0;
## Filter filenames from the directory that match criteria of OP.
my @files = grep { -d $_ && m/\A(\d+)\s-\s.*\1/ } map { basename $_ } <./*>;
## Get numbers in reverse mode to substitute them later in filenames .
my @nums = map { m/\A(\d+)/; $1 || 0 } reverse @files;
## Process all files, change the number of the file and rename it.
for my $file ( @files ) {
(my $new_file = $file) =~ s/\A(\d+)/shift @nums/e;
if ( $real ) {
rename $file, $new_file or warn qq|WARN: Couldn't rename "$file"\n|;
}
else {
printf qq|%s\n|, qq|rename "$file" "$new_file"|;
}
}
列出目录:
ls -1
通过下面的输出:
1 - file1file
2 - fi2le
3 - fileeee3
4 - fou4r
5 - donttouch
6 - donttouch5either
script.pl
运行脚本:
perl script.pl
再次列出directoy:
list the directoy again:
ls -1
通过下面的输出:
1 - fou4r
2 - fileeee3
3 - fi2le
4 - file1file
5 - donttouch
6 - donttouch5either
script.pl
修改:有在评论中让前真正的试运行的建议,所以我增加了一个参数真正
或试验
。有了第一个选项会做真正的变化,同时与第二个它会打印
来输出真正的命令,但不运行它们。现在运行类似的脚本:
EDIT: There was a suggestion in comments to let a trial run before the real one, so I added an argument real
or trial
. With first option it will do real changes, while with second one it will print
to output the real command but without running them. Now run the script like:
perl script.pl real
或
perl script.pl trial
这篇关于批量重命名以相反的顺序目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!