find and replace a word with another in all file n

2019-03-04 05:49发布

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

标签: linux shell grep
2条回答
小情绪 Triste *
2楼-- · 2019-03-04 06:12

If you don't have rename installed, this should be a reasonable alternative (assuming bash as your shell):

while read entry
do
  mv "${entry}" "${entry/owner/user}"
done < <(find . -depth -name '*owner*' -print)
查看更多
叛逆
3楼-- · 2019-03-04 06:22

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

查看更多
登录 后发表回答