使用perl重命名文件名的一部分

时间:2014-01-21 23:04:43

标签: perl

我想使用perl重命名部分文件。我知道如何重命名具有空格的文件名,我为文件名称设置了“my 123.log”。此代码将其重命名为new_123.log。

foreach my $i (<"my *.log">) {

my $y = $i; # save the original file name

$i =~ s/my /new_/; # replace the spaces with a _ character

rename ( $y, $i ); # rename the original file with the new name

现在我想重命名名为my.123.log的文件,我很困惑如何处理这个'。'在文件名中。另外如果我想重命名一个以我的名字开头的文件名(以免说我的123.log),那么这个命令好吗?我想使用它,因为我只知道文件名的开头

move '../my *.log', '../new.log' or die "cant change the name";

1 个答案:

答案 0 :(得分:1)

我认为您希望在将模式交给move之前找到该模式。上面的move语句将覆盖除最后一个之外的所有输入文件。因此,您可以“保存”使用parens匹配的内容(一次或多次):

/^my\s([a-z0-9])\.log/;

#try this first please
print "move '../my $1.log', '../new$1.log' or die "cant _overwrite_ the file";

#and if that looks ok then try uncommenting this:
#move '../my $1.log', '../new$1.log' or die "cant _overwrite_ the file";

我没有时间测试我的正则表达式,可能需要将字符类匹配修改为一次或多次,或者如果您认为字母数字以外的字符将在文件名中,则扩展。

相关问题