Perl删除空格 - 将文件复制到新名称

时间:2015-04-05 04:51:32

标签: perl

我已经下载了名称中带有空格的文件。 我想用underbars替换空格 - 最终我想改变文件的名称 - 去掉空格并且没有空格的名字。我将使用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" ;
    }
}

我想要实现的是这样的输出 - 你看到我们有原始文件名的空格,然后更新的文件名与underbar(我喜欢它更好的名称没有空格!):

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旧文件转移到新文件。 howevers 这是我得到的输出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

数字在输出中非常混乱。

2 个答案:

答案 0 :(得分:1)

以下行不会将新名称分配给$ undebar:

my $underbar = $desktop_item =~ s/ /_/g;

标量上下文中的替换返回替换的数量。见perlop

  

在字符串中搜索模式,如果找到,则用替换文本替换该模式,并返回所做的替换次数。

常见的习语是首先进行分配,然后进行替换:

(my $underbar = $desktop_item) =~ s/ /_/g;

或者,从5.14开始,您可以使用/r修饰符:

my $underbar = $desktop_item =~ s/ /_/gr;

答案 1 :(得分:0)

此行=> my $underbar = $desktop_item =~ s/ /_/g; $ underbar在给定字符串中存储正则表达式匹配的数量(在您的情况下为空格)。

相关问题