对带撇号的文件进行“重命名”

对带撇号的文件进行“重命名”

我正在尝试使用该rename实用程序(特别是 perl 版本,即prename)批量重命名一些文件。不幸的是,文件名包含撇号,这会弄乱一切。我不确定如何继续。

这是我尝试过的:

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

正确的语法是什么?

答案1

  1. 您的最后一个变体是在双引号内使用单引号的正确变体 - 但您还必须转义,$1否则 shell 将扩展它:

    "/.*(\d\d).jpg/Foo's Excellent Photo - \$1.jpg/"
    
  2. 但是我仍然收到错误

    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 "
    

    但这不是因为引用错误,而是因为perl-rename需要 perl 正则表达式。而且您显然想要搜索和替换,因此请使用s/.../.../,而不仅仅是/.../.../

  3. 因此,总而言之,这个命令运行完美:

    $ 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
    

相关内容