使用反引号时,请跳出空格 [英] Escape whitespace when using backticks

查看:216
本文介绍了使用反引号时,请跳出空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个搜索,从我的角度来看,使用反引号是我可以解决这个问题的唯一办法。我试图从Perl中调用目录中每个文件的 mdls 命令来查找它的上次访问时间。我遇到的问题是,在我从 find 的文件名中找到了非空格的空格,而bash显然不喜欢这个空格。是否有一种简单的方法可以在将文件传递给 mdls 之前,将所有文件名中的空格转义出来。请原谅,如果这是一个明显的问题。我对Perl很陌生。

  my $ top_dir ='/ Volumes / hydrogen / FLAC'; ($ File :: Find :: name){
我的$ curr_file_path = $ File :: Find :: name。
$ b $ sub想要{#了解子例程
。 \\\
;
`mdls $ curr_file_path`;
print $ _;
}
}

find(\& wanted,$ top_dir);


解决方案

如果您确定文件名不包含换行符(CR或LF),几乎所有的Unix shell都接受反斜杠引用,而Perl有 quotemeta 函数来应用它。

  my $ curr_file_path = quotemeta($文件::查找::名); 
my $ time =`mdls $ curr_file_path`;

不幸的是,这对于带有换行符的文件名不起作用,因为shell处理一个反斜杠后跟一个换行符是通过删除两个字符而不是只是反斜杠。所以为了安全起见,请使用 String :: ShellQuote

 使用String :: ShellQuote; 
...
my $ curr_file_path = shell_quote($ File :: Find :: name);
my $ time =`mdls $ curr_file_path`;

对于包含除NUL字符以外任何内容的文件名都是可以的,文件名。



这两种解决方案都只适用于Unix风格的shell。如果你在Windows上,适当的shell引用是非常棘手的。


I've had a search around, and from my perspective using backticks is the only way I can solve this problem. I'm trying to call the mdls command from Perl for each file in a directory to find it's last accessed time. The issue I'm having is that in the file names I have from find I have unescaped spaces which bash obviously doesn't like. Is there an easy way to escape all of the white space in my file names before passing them to mdls. Please forgive me if this is an obvious question. I'm quite new to Perl.

my $top_dir = '/Volumes/hydrogen/FLAC';

sub wanted { # Learn about sub routines 
    if ($File::Find::name) { 
         my $curr_file_path = $File::Find::name. "\n";
        `mdls $curr_file_path`;
         print $_;
    }
}

find(\&wanted, $top_dir);

解决方案

If you're sure the filenames don't contain newlines (either CR or LF), then pretty much all Unix shells accept backslash quoting, and Perl has the quotemeta function to apply it.

my $curr_file_path = quotemeta($File::Find::name);
my $time = `mdls $curr_file_path`;

Unfortunately, that doesn't work for filenames with newlines, because the shell handles a backslash followed by a newline by deleting both characters instead of just the backslash. So to be really safe, use String::ShellQuote:

use String::ShellQuote;
...
my $curr_file_path = shell_quote($File::Find::name);
my $time = `mdls $curr_file_path`;

That should work on filenames containing anything except a NUL character, which you really shouldn't be using in filenames.

Both of these solutions are for Unix-style shells only. If you're on Windows, proper shell quoting is much trickier.

这篇关于使用反引号时,请跳出空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆