代码之家  ›  专栏  ›  技术社区  ›  goldenmean

如何处理带有空格的文件名?

  •  8
  • goldenmean  · 技术社区  · 15 年前

    我在windows上使用Perl(activeperl)。我有一个perl程序来将当前文件夹中的文件全局化,并使用从内部使用system()调用的dos copy命令将它们连接起来。。。

    当我执行时,会出现一个dos错误,说“系统找不到指定的文件”,这与我在文件名中的空格有关。

    这是perl代码:-

    @files = glob "*.mp3";
    $outfile = 'final.mp3';
    $firsttime = 1;
    foreach (@files)
    {
    
        if($firsttime == 1)
        {
           @args = ('copy' ,"/b ","$_","+","$outfile", "$outfile");
           system (@args);
           #system("copy /b '$_'+$outfile $outfile"); 
           $firsttime = 0;  
        }
        else
        {
           @args = ('copy' ,"/b ","$outfile","+","$_", "$outfile");
           system (@args);
           #system("copy /b $outfile+'$_' $outfile"); 
        }
    
    }
    

    glob返回当前文件夹中的文件名数组,这些文件名之间有空格,因此数组元素之间有空格。如上图所示,当我使用系统(…)在使用“$”的数组元素上执行copy命令时,会出现如上所示的错误。

    我尝试了几种方法来调用系统(…),但都没有成功。

    我想知道,

    1]如何使用上面的代码处理文件之间有空格的文件。如何“转义”文件名中的空白。

    2]Perl中的任何替代解决方案都可以实现相同的功能。(欢迎简单的……)

    6 回复  |  直到 10 年前
        1
  •  9
  •   Ed Guiness    15 年前

    您的代码不会在文件名周围添加任何引号。

    尝试

    "\"$_\""
    

    "\"$outfile\""
    
        2
  •  11
  •   Ian C.    15 年前

    停止使用 system() 打一个可以用便携式图书馆完成的电话。Perl有一个 File::Copy 模块,使用它,您不必担心这样的事情,而且您可以获得更好的操作系统可移植性。

        3
  •  7
  •   grawity_u1686    15 年前

    system 很少是正确的答案, use File::Copy ;

    要连接所有文件:

    use File::Copy;
    my @in = glob "*.mp3";
    my $out = "final.mp3";
    
    open my $outh, ">", $out;
    for my $file (@in) {
        next if $file eq $out;
        copy($file, $outh);
    }
    close $outh;
    
        4
  •  1
  •   Ruel    15 年前

    当您试图访问变量时,可能会出现问题 $_ 在内部块内。最安全的方法,改变:

    foreach (@files)
    

    致:

    foreach $file (@files)
    

    然后在上进行必要的更改 @args ,并转义双引号以将其包含在字符串中。。

    @args = ('copy' ,"/b ","\"$file\"","+","$outfile", "$outfile");
    ...
    @args = ('copy' ,"/b ","$outfile","+","\"$file\"", "$outfile");
    
        5
  •  1
  •   Viper_Sb    15 年前

    在windows中,通常可以在文件名(和/或路径)周围加上双引号,允许使用特殊字符,即“长文件名”。

    C:\“我的长路径\这是一个文件.mp3”

    编辑:

    这不管用吗?

    system("copy /b \"$_\"+$outfile $outfile");
    

    (注意字符串中的双引号而不是单引号)

        6
  •  0
  •   user3784340    9 年前

    $filename=~s/\/\/;

    文件名只是用斜杠来表示空格