如何在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
相关但不完全是解释性的:
Relevant but not completely explanatory:
- How can I batch rename files using the Terminal?
- Regex to batch rename files in OS X Terminal
推荐答案
在您的特定情况下,您可以使用以下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
的应用程序参数扩展:将(第一个)子字符串匹配模式_*_
替换为文字_
,有效地从名称中删除了中间标记. - 请注意,
_*_
是 pattern (通配符表达式,也用于通配符),而不是正则表达式(要了解模式,请运行,然后搜索 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]大多数实用程序都支持特殊参数--
的目的是表示应将后续参数视为操作数(值),即使它们 look 类似于 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屋!