我已经下载了这些文件的名字中的空格。我想用下面的栏替换空格--最终我想要更改文件的名称--以摆脱空格,并有没有空格的名称。我将使用File::Copy来对文件名进行更改,但是现在我希望保留旧的文件名,这样我就可以将文件的内容复制到新的名称中。
$ ls | perl -nle 'print if /\w\s.[jpg|png|pdf]/'
ls | perl -nle 'print if /\w\s.[jpg|png|pdf]/'
Effective awk Programming, 3rd Edition.pdf
Fashion Photography by Edward Steichen in the 1920s and 1930s (15).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (19).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (30).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (4).jpg
sed & awk, 2nd Edition.pdf我使用这个代码,但它有许多困难,并造成许多恐慌。
#!/usr/bin/perl
use strict
opendir my $dir, "/cygdrive/c/Users/walt/Desktop" or die "Cannot open directory: $!";
my @files = readdir $dir;
closedir $dir;
foreach my $desktop_item (@files) {
if ($desktop_item =~ /\w\s.[jpg|png|pdf]/) {
my $underbar = $desktop_item =~ s/ /_/g;
print "$desktop_item\n" ;
print "$underbar\n" ;
}
}我试图实现的是这样的输出--您可以看到,我们有原始的文件名和空格,然后有更新的文件名(我更喜欢没有空格的名称!):
Effective_awk_Programming,_3rd_Edition.pdf
Effective awk Programming, 3rd Edition.pdf
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(15).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (15).jpg
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(19).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (19).jpg
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(30).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (30).jpg
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(4).jpg
Fashion Photography by Edward Steichen in the 1920s and 1930s (4).jpg
sed_&_awk,_2nd_Edition.pdf
sed & awk, 2nd Edition.pdf最终,我将目标cp旧文件到新文件。这是我得到的输出L:
./rename_jpg.pl
Effective_awk_Programming,_3rd_Edition.pdf
4
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(15).jpg
10
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(19).jpg
10
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(30).jpg
10
Fashion_Photography_by_Edward_Steichen_in_the_1920s_and_1930s_(4).jpg
10
sed_&_awk,_2nd_Edition.pdf
4这些数字在输出中非常混乱。
发布于 2015-04-05 05:45:54
下面的行不对$undebar使用新的名称:
my $underbar = $desktop_item =~ s/ /_/g;标量上下文中的替换返回替换的数量。请参阅佩洛普
在字符串中搜索模式,如果找到,则用替换文本替换该模式,并返回所做的替换数量。
常见的成语是先做作业,然后再做替换:
(my $underbar = $desktop_item) =~ s/ /_/g;或者,从5.14开始,您可以使用/r修饰符:
my $underbar = $desktop_item =~ s/ /_/gr;发布于 2015-04-05 05:46:27
在这一行中,=> my $underbar = $desktop_item =~ s/ /_/g; $underbar以给定的字符串存储正则表达式匹配的数量(在您的情况下是空格)。
https://stackoverflow.com/questions/29454222
复制相似问题