开发者

Escaping brackets in file names

I've got开发者_JS百科 a few files named stuff like this: file (2).jpg. I'm writing a little Perl script to rename them, but I get errors due to the brackets not being replaced. So. Can someone tell me how to escape all the brackets (and spaces, if they cause a problem) in a string so I can pass it to a command. The script is below:

#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");
}

The error is this:

Can't call method "Q" without a package or object reference at script.sh line [problem line].

This is my first time with regex, so I'm looking for the answers that explain what to do as well as giving an answer. Thanks for any help.


Why do not use a simple?

find . -name \*.JPG -exec exiv2 -r "%Y_%m%d_%H%M%S" "{}" \;

Ps: The \Q disabling pattern metacharacters until \E inside the regex.

For example, if you want match a path "../../../somefile.jpg", you can write:

$file =~ m:\Q../../../somefile.jpg\E:;

instead of

$file =~ m:\.\./\.\./\.\./somefile\.jpg:; #e.g. escaping all "dots" what are an metacharacter for regex.


I found this perl renaming script that was written by Larry Wall a while back... it does what you need and so much more. I keep in in my $PATH, and use it daily...

#!/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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜