[英]how to change names of all directories / files containing a specific string on linux
我有一个目录,我想将其下的所有目录名称和文件更改为不同的名称。 例如我的目录结构是
./mydir_ABC/
./mydir_ABC/myfile_ABC.txt
./mydir_ABC/otherdir_ABC/
例如,我想做到
./mydir_DEF/
./mydir_DEF/myfile_DEF.txt
./mydir_DEF/otherdir_DEF/
我在用
find . -type 'f' -name '*ABC*'
find . -type 'd' -name '*ABC*'
获取名称中包含我的字符串的所有相关目录和文件的列表。 我如何将 pipe 转换为另一个实际更改目录名和文件名的命令? (如果文件或目录已经存在,我希望它能够覆盖。)
mkdir z; cd z; touch fooabcbar; touch fooABCbar
find . -type 'f' \( -name '*ABC*' -o -name '*abc*' \) | while read f; do g=`echo "$f" | sed -e 's/abc/def/g' -e 's/ABC/DEF/g'`; echo mv -- "$f" "$g"; done
只要路径名不包含换行符(非常罕见)。
查找rename(1)
命令。 它有一些不同的变体,但它们都支持基于某种正则表达式的某种重命名。 我使用的版本(基于 Perl 'Camel Book' 第一版的代码)将用作:
rename 's%ABC%DEF%g' ...
或者,对于您的示例:
find . -print0 | xargs -0 rename s/ABC/DEF/g
或者,为了避免在遍历目录结构时路径名发生更改的问题,请先执行目录名,然后是文件(如问题所示):
find . -type d -print0 | xargs -0 rename s/ABC/DEF/g
find . -type f -print0 | xargs -0 rename s/ABC/DEF/g
像 go 那样重命名目录仍然可能存在问题(因为一旦将./DEF
./ABC
您就不能再将./ABC/subABC/
重命名为./DEF/subDEF
因为目录现在是./DEF/subABC
)。
其他版本的rename
有不同的语法 - 请查看您的手册页。
这是基于 Perl 的rename
版本,源自 Perl 'Camel Book' 的第一版; 我在版本控制下的第一个版本的日期为 1992-01-05。 今天的更改更新了 shebang 行(使用 env,删除-w
因为它不可靠,并添加了use warnings;
以弥补 no -w
)。 之前的变化是 2008 年、1998 年、1996 年和 1992 年; 在过去的 19 年里,它并没有太大变化。
#!/usr/bin/env perl
#
# @(#)$Id: rename.pl,v 1.8 2011/06/03 22:30:22 jleffler Exp $
#
# Rename files using a Perl substitute or transliterate command
use strict;
use warnings;
use Getopt::Std;
my(%opts);
my($usage) = "Usage: $0 [-fnxV] perlexpr [filenames]\n";
my($force) = 0;
my($noexc) = 0;
my($trace) = 0;
die $usage unless getopts('fnxV', \%opts);
if ($opts{V})
{
printf "%s\n", q'RENAME Version $Revision: 1.8 $ ($Date: 2011/06/03 22:30:22 $)';
exit 0;
}
$force = 1 if ($opts{f});
$noexc = 1 if ($opts{n});
$trace = 1 if ($opts{x});
my($op) = shift;
die $usage unless defined $op;
if (!@ARGV) {
@ARGV = <STDIN>;
chop(@ARGV);
}
for (@ARGV)
{
if (-e $_ || -l $_)
{
my($was) = $_;
eval $op;
die $@ if $@;
next if ($was eq $_);
if ($force == 0 && -f $_)
{
print STDERR "rename failed: $was - $_ exists\n";
}
else
{
print "+ $was --> $_\n" if $trace;
print STDERR "rename failed: $was - $!\n"
unless ($noexc || rename($was, $_));
}
}
else
{
print STDERR "$_ - $!\n";
}
}
如果它总是最后 3 个字符,这应该足够好我认为:
mv *abc.* *def.*
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.