【问题标题】:How to rename folders and files recursively in MacOS如何在 MacOS 中递归地重命名文件夹和文件
【发布时间】:2014-02-07 13:52:24
【问题描述】:

我曾经有一台 Debian 机器,我记得使用过类似的东西:

shopt -s globstar
rename 's/changethis/tothis/' **

但也许是因为我得到的 bash 版本(版本 3.2.48(1))不是最新的:

-bash: shopt: globstar: invalid shell option name
-bash: rename: command not found

在 OS X 中递归重命名文件和文件夹有什么不同的方法? (10.8.5)


我想将每个包含sunshine 字符串的文件夹和文件重命名为sunset。所以文件: post_thumbnails_sunshine 将变为 post_thumbnails_sunsetr_sunshine-new 将变为 r_sunset-new 等等。

【问题讨论】:

  • 一方面,rename 似乎是第三方实用程序:plasmasturm.org/code/rename。 (在 Homebrew 上可用。)globstar 是 Bash 4.0 中的新功能:linuxjournal.com/content/globstar-new-bash-globbing-option
  • 您希望在命令提示符下直接使用 unix 命令。比如:find . -name "from_this" -exec mv {} to_this \;
  • @mbratch 这只会替换完全匹配.. 我还想将 changethis-one 等文件重命名为 tothis-one
  • 我没有关注。您的新替换示例不显示任何通配符,问题陈述中的示例也不显示。您能否在问题描述中进一步解释您要重命名的内容?你有一个要重命名的列表吗?还是一种模式?
  • @mbratch 为问题添加了模式。

标签: macos bash recursion rename


【解决方案1】:
 find . -depth -name "*from_stuff*" -execdir sh -c 'mv {} $(echo {} | sed "s/from_stuff/to_stuff/")' \;

【讨论】:

  • 你应该避免使用反引号。 $() 更好。
  • @Sebastian 感谢您发现这一点,我同意(已编辑)。
【解决方案2】:

这应该可以解决问题:

find . -name '*sunshine*' | while read f; do mv "$f" "${f//sunshine/sunset}"; done

*专门重命名文件使用-type f,目录使用-type d

【讨论】:

    【解决方案3】:

    您可以在 find 命令中使用正则表达式,如 cmets 中的 @mbratch 所述。您可以使用-regex-iregex-regextypefind 提供完整的表达式。然后调用-exec mv {} +(注意+ 符号)。

    【讨论】:

      猜你喜欢
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-23
      • 2017-10-27
      • 1970-01-01
      • 2018-11-28
      • 2017-08-18
      • 2014-07-12
      相关资源
      最近更新 更多