‘rename’ on files with apostrophes

bashrename

I'm trying to batch rename some files using the rename utility (specifically the perl version, i.e. prename). Unfortunately, the file names contain apostrophes, and it's messing things up. I'm not sure how to proceed.

Here's what I've tried:

rename -n '/.*(\d\d).jpg/Foo's Excellent Photo - $1.jpg/'  # fails due to end of string
rename -n '/.*(\d\d).jpg/Foo\'s Excellent Photo - $1.jpg/' # fails due to end of string
rename -n "/.*(\d\d).jpg/Foo's Excellent Photo - $1.jpg/"  # fails due to shell expansion

What is the correct syntax?

Best Answer

  1. Your last variant is the correct one to use single inside double quotes -- but you have to escape also the $1 otherwise the shell will expand it:

    "/.*(\d\d).jpg/Foo's Excellent Photo - \$1.jpg/"
    
  2. However, I still get the error

    Bareword found where operator expected at (eval 1) line 1, near "/.*(\d\d).jpg/Foo's"
        (Missing operator before Foo's?)
    syntax error at (eval 1) line 1, near "/.*(\d\d).jpg/Foo's Excellent "
    

    But this is not because of wrong quoting, but because perl-rename expects a perl regex. And you obviously want to search and replace, so use s/.../.../, not only /.../.../.

  3. So, summing up, this command works flawlessly:

    $ rename -n  "s/.*(\d\d).jpg/Foo's Excellent Photo - \$1.jpg/" *
    PIC44.jpg renamed as Foo's Excellent Photo - 44.jpg
    PIC45.jpg renamed as Foo's Excellent Photo - 45.jpg
    
Related Question