使用反引号时,请跳出空格 [英] Escape whitespace when using backticks
问题描述
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屋!