在目录的所有文件名中查找并替换另一个单词 [英] find and replace a word with another in all file names of a directory

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

问题描述

我尝试在我的目录(以及所有子目录)的所有文件名中将owner替换为user。

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

任何帮助将不胜感激

find 与 -exec 选项调用在其名称中包含 owner 的每个文件和子目录中重命名

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

如果您没有 rename ,您可以使用 mv 命令与 bash 参数展开:

  find / old /{}; new =$ {old#} / #* /}; echo$ {old%/ *} / $ {new / owner / user})'\; 

bash -c'...'在由单引号括起来的单行程中调用bash shell。单线程用作 mv 命令,该命令将匹配的文件名/子目录的基本名称中的所有 owner 重命名为用户



具体来说, find 替换每个 {} / code>后面的 -exec 与匹配的文件/子目录的路径名。这里 mv 接受两个参数;第一个是 {} (如前所述),第二个是从子shell $(...)包含三个bash命令。这些bash命令使用参数扩展技术进行重命名基本名称 {}


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

Ex.

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

Any help would be appreciated

解决方案

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 {} \+

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 '...' 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".

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 {}.

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

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