且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为所有图像添加前缀(递归)

更新时间:2023-12-01 10:23:16

可能的解决方案之一:

find . -name '*.jpg' -printf "'%p' '%h/thumb_%f'\n" | xargs -n2  echo mv

Principe:找到所有需要的文件,并为标准mv命令准备参数.

Principe: find all needed files, and prepare arguments for the standard mv command.

注意:

  • 参数由'包围,以允许在文件名中使用空格.
  • 缺点是:与许多mp3文件一样,它不适用于包含'撇号本身的文件名.如果您需要移动更奇怪的文件名,请在下面检查.
  • 以上命令用于空运行(仅显示带有args的mv命令).对于实际工作,请删除echo假装mv.
  • arguments for the mv are surrounded by ' for allowing spaces in filenames.
  • The drawback is: this will not works with filenames what are containing ' apostrophe itself, like many mp3 files. If you need moving more strange filenames check bellow.
  • the above command is for dry run (only shows the mv commands with args). For real work remove the echo pretending mv.

任何文件名重命名.在外壳中,您需要一个定界符.问题在于,通常文件名(存储在shell变量中)通常可以包含分隔符本身,因此:

ANY filename renaming. In the shell you need a delimiter. The problem is, than the filename (stored in a shell variable) usually can contain the delimiter itself, so:

mv $file $newfile         #will fail, if the filename contains space, TAB or newline
mv "$file" "$newfile"     #will fail, if the any of the filenames contains "

正确的解决方案是:

  • 使用适当的转义符准备文件名
  • 使用容易理解任何文件名的脚本语言

可以使用内部的printf%q格式指令= print quoted bash 中准备正确的转义.但是这种解决方案很长而且很无聊.

Preparing the correct escaping in bash is possible with it's internal printf and %q formatting directive = print quoted. But this solution is long and boring.

恕我直言,最简单的方法是使用perl并使用零填充的print0,如下所示.

IMHO, the easiest way is using perl and zero padded print0, like next.

find . -name \*.jpg -print0 | perl -MFile::Basename -0nle 'rename $_, dirname($_)."/thumb_".basename($_)'

以上使用perl的功能来整理文件名,并最终重命名文件.

The above using perl's power to mungle the filenames and finally renames the files.