本文介绍了在目录的所有文件名中查找单词并将其替换为另一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的目录(以及所有子目录)的所有文件名中的所有者"一词替换为用户".

I'm trying to replace the word "owner" with "user" in all file names of my directory (and in all subdirectories).

例如

owners_controller => users_controller
owner.rb => user.rb

任何帮助将不胜感激

推荐答案

使用 find-exec 选项来调用 rename名称中包含owner"的文件和子目录:

Use find with the -exec option to call rename on every file and subdirectory containing "owner" in its name:

find path/to/my/directory/ -depth -name "*owner*" -exec /usr/bin/rename owner user {} +

如果你没有rename,你可以使用带有bash参数扩展的mv命令:

If you don't have rename, you can use a mv command with bash parameter expansion:

find path/to/my/directory/ -depth -name "*owner*" -exec
  bash -c 'mv "{}" $(old="{}"; new="${old##*/}"; echo "${old%/*}/${new/owner/user}")' ;

bash -c '...' 在单引号包围的单行上调用 bash shell.单行作为 mv 命令,将匹配文件名/子目录的基本名称中所有出现的owner"重命名为user".

bash -c '...' invokes the bash shell on the one-liner surrounded by single-quotes. The one-liner acts as a mv command that renames all occurrences of "owner" in the basename of the matching filename/subdirectory to "user".

具体来说,find-exec 之后的每个 {} 替换为匹配的文件/子目录的路径名.这里 mv 接受两个参数;第一个是 {}(之前描述过),第二个是从包含三个 bash 命令的子 shell $(...) 返回的字符串.这些 bash 命令使用参数扩展技术来重命名{} 的基本名称.

Specifically, find substitutes every {} after the -exec with the matching file/subdirectory's pathname. Here mv accepts two arguments; the first is {} (described previously), and the second is a string returned from a sub-shell $(...) containing three bash commands. These bash commands use parameter expansion techniques to rename the basename of {}.

这篇关于在目录的所有文件名中查找单词并将其替换为另一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:38