我有几个文件名为:file (2).jpg
。我正在写一个小的Perl脚本来重命名它们,但由于括号没有被替换,我得到错误。的所以即可。有人可以告诉我如何在字符串中转义所有括号(和空格,如果它们引起问题),这样我就可以将它传递给命令。脚本如下:
#Load all jpgs into an array. @pix = `ls *.JPG`; foreach $pix (@pix) { #Let you know it's working print "Processing photo ".$pix; $pix2 = $pix; $pix2 =~ \Q$pix\E; # Problem line #Use the program exiv2 to rename the file with timestamp system("exiv2 -r %Y_%m%d_%H%M%S $pix2"); }
错误是这样的:
Can't call method "Q" without a package or object reference at script.sh line [problem line].
这是我第一次使用正则表达式,所以我正在寻找解释该做什么以及给出答案的答案。谢谢你的帮助。
答案 0 :(得分:2)
为什么不使用简单的?
find . -name \*.JPG -exec exiv2 -r "%Y_%m%d_%H%M%S" "{}" \;
PS: \ Q禁用模式元字符,直到正则表达式中的\ E 。
例如,如果你想匹配路径“../../../somefile.jpg”,你可以写:
$file =~ m:\Q../../../somefile.jpg\E:;
而不是
$file =~ m:\.\./\.\./\.\./somefile\.jpg:; #e.g. escaping all "dots" what are an metacharacter for regex.
答案 1 :(得分:1)
我发现这个由Larry Wall编写的perl重命名脚本一段时间后......它可以满足您的需求,还有更多。我保留在我的$ PATH中,每天使用它......
#!/usr/bin/perl -w
use Getopt::Std;
getopts('ht', \%cliopts);
do_help() if( $cliopts{'h'} );
#
# rename script examples from lwall:
# pRename.pl 's/\.orig$//' *.orig
# pRename.pl 'y/A-Z/a-z/ unless /^Make/' *
# pRename.pl '$_ .= ".bad"' *.f
# pRename.pl 'print "$_: "; s/foo/bar/ if <stdin> =~ /^y/i' *
$op = shift;
for (@ARGV) {
$was = $_;
eval $op;
die $@ if $@;
unless( $was eq $_ ) {
if( $cliopts{'t'} ) {
print "mv $was $_\n";
} else {
rename($was,$_) || warn "Cannot rename $was to $_: $!\n";
}
}
}
sub do_help {
my $help = qq{
Usage examples for the rename script example from Larry Wall:
pRename.pl 's/\.orig\$//' *.orig
pRename.pl 'y/A-Z/a-z/ unless /^Make/' *
pRename.pl '\$_ .= ".bad"' *.f
pRename.pl 'print "\$_: "; s/foo/bar/ if <stdin> =~ /^y/i' *
CLI Options:
-h This help page
-t Test only, do not move the files
};
die "$help\n";
return 0;
}