Bash脚本: 文件批量重命名 包括子文件夹

2019-03-05  本文已影响1人  汶水一方

假如你有一个多层级文件夹,它包含了很多jpg文件以及子文件夹(也有jpg文件)。现在你想把所有文件批量重命令,比如把jpg扩展名改为png,或者把里面的IMG字符改为abc,可以用下面的命令。

新建一个文件(比如file.sh),内容如下,并用chmod a+x file.sh命令赋予可执行权限。

#!/bin/bash
find . -type f -name '*.jpg' -exec sh -c '
  for f; do mv "$f" "${f//.jpg/.png}";
  done' sh {} +

从左到右依次解释如下

另外:

  1. 如果想指定目录深度(比如2级),可以使用-maxdepth 2,如果设置为1则只查找当前目录。

  2. 关于-exec command {} +的详细说明,参考这里

-exec command {} +
This variant of the -exec option runs the specified command on the selected files, but the command line is built by appending each selected file name at the end; the total number of invocations of the command will be much less than the number of matched files. The command line is built in much the same way that xargs builds its command lines. Only one instance of '{}' is allowed within the command. The command is executed in the starting directory.

在macOS 10.13.6 High Sierra上测试通过。

上一篇 下一篇

猜你喜欢

热点阅读