如何在 macOS 终端中批量重命名文件? [英] How to Batch Rename Files in a macOS Terminal?
问题描述
我有一个文件夹,里面有一系列名为:
I have a folder with a series of files named:
prefix_1234_567.png
prefix_abcd_efg.png
我想批量删除一个下划线和中间的内容,所以输出是:
I'd like to batch remove one underscore and the middle content so the output would be:
prefix_567.png
prefix_efg.png
相关但不完全说明:
推荐答案
在您的特定情况下,您可以使用以下 bash
命令(bash
是 macOS 上的默认 shell):
In your specific case you can use the following bash
command (bash
is the default shell on macOS):
for f in *.png; do echo mv "$f" "${f/_*_/_}"; done
注意:如果您的文件名可能以 -
开头,请将 --
放在它们之前[1]:mv -- "$f" "${f/_*_/_}"
Note: If there's a chance that your filenames start with -
, place --
before them[1]:
mv -- "$f" "${f/_*_/_}"
注意:echo
被添加到 mv
之前,以便执行试运行.删除它以执行实际重命名.
Note: echo
is prepended to mv
so as to perform a dry run. Remove it to perform actual renaming.
您可以从命令行运行它或在脚本中使用它.
You can run it from the command line or use it in a script.
"${f/_*_/_}"
是bash
参数扩展:(第一个)子串匹配模式_*_
被替换为文字_
,有效地从名称中删除中间标记.- 请注意,
_*_
是一个 模式(通配符表达式,也用于通配符),而不是正则表达式(用于了解模式,运行man bash
并搜索Pattern Matching
).
"${f/_*_/_}"
is an application ofbash
parameter expansion: the (first) substring matching pattern_*_
is replaced with literal_
, effectively cutting the middle token from the name.- Note that
_*_
is a pattern (a wildcard expression, as also used for globbing), not a regular expression (to learn about patterns, runman bash
and search forPattern Matching
).
如果您发现自己经常批量重命名文件,考虑安装一个专门的工具,比如基于 Perl 的 rename
实用程序.在 macOS 上,您可以使用流行的包管理器 Homebrew 安装它,如下所示:
If you find yourself batch-renaming files frequently, consider installing a specialized tool such as the Perl-based rename
utility.
On macOS you can install it using popular package manager Homebrew as follows:
brew install rename
这是使用 rename
的顶部命令的等效项:
Here's the equivalent of the command at the top using rename
:
rename -n -e 's/_.*_/_/' *.png
再次,此命令执行试运行;删除 -n
以执行实际重命名.
Again, this command performs a dry run; remove -n
to perform actual renaming.
- 类似于
bash
解决方案,s/.../.../
执行文本替换,但 - 与bash
不同 -使用了真正的正则表达式.
- Similar to the
bash
solution,s/.../.../
performs text substitution, but - unlike inbash
- true regular expressions are used.
[1] 大多数实用程序都支持的特殊参数 --
的目的是表明后续参数应被视为操作数(值),即使它们看起来像 options 因为以 -
开头,如 Jacob C. 注释.
[1] The purpose of special argument --
, which is supported by most utilities, is to signal that subsequent arguments should be treated as operands (values), even if they look like options due to starting with -
, as Jacob C. notes.
这篇关于如何在 macOS 终端中批量重命名文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!