如何在 macOS 终端中批量重命名文件? [英] How to Batch Rename Files in a macOS Terminal?

查看:36
本文介绍了如何在 macOS 终端中批量重命名文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件夹,里面有一系列名为:

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 of bash 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, run man bash and search for Pattern 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 in bash - 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆