在 Linux 中查找多个文件并重命名它们

新手上路,请多包涵

我在 Suse 10 系统中有像 a_dbg.txt, b_dbg.txt ... 这样的文件。我想编写一个 bash shell 脚本,它应该通过从中删除“_dbg”来重命名这些文件。

谷歌建议我使用 rename 命令。所以我在 rename _dbg.txt .txt *dbg* CURRENT_FOLDER

我的实际 CURRENT_FOLDER 包含以下文件。

 CURRENT_FOLDER/a_dbg.txt
CURRENT_FOLDER/b_dbg.txt
CURRENT_FOLDER/XX/c_dbg.txt
CURRENT_FOLDER/YY/d_dbg.txt

执行 rename 命令后,

 CURRENT_FOLDER/a.txt
CURRENT_FOLDER/b.txt
CURRENT_FOLDER/XX/c_dbg.txt
CURRENT_FOLDER/YY/d_dbg.txt

它不是递归的,如何使这个命令重命名所有子目录中的文件。像 XXYY 我会有这么多子目录,这些子目录的名称是不可预测的。而且我的 CURRENT_FOLDER 也会有一些其他文件。

原文由 rashok 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 998
2 个回答

您可以使用 find 递归查找所有匹配的文件:

 $ find . -iname "*dbg*" -exec rename _dbg.txt .txt '{}' \;


编辑: '{}'\; 是什么?

-exec 参数使 find 对找到的每个匹配文件执行 rename'{}' 将替换为文件的路径名。最后一个标记 \; 仅用于标记 exec 表达式的结束。

所有这些都在 find 的手册页中有很好的描述:

  -exec utility [argument ...] ;
         True if the program named utility returns a zero value as its
         exit status.  Optional arguments may be passed to the utility.
         The expression must be terminated by a semicolon (``;'').  If you
         invoke find from a shell you may need to quote the semicolon if
         the shell would otherwise treat it as a control operator.  If the
         string ``{}'' appears anywhere in the utility name or the argu-
         ments it is replaced by the pathname of the current file.
         Utility will be executed from the directory from which find was
         executed.  Utility and arguments are not subject to the further
         expansion of shell patterns and constructs.

原文由 kamituel 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于递归重命名,我使用以下命令:

 find -iname \*.* | rename -v "s/ /-/g"

原文由 Gantan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题