find and replace a word with another in all file names of a directory

后端 未结 2 572
广开言路
广开言路 2021-01-27 12:37

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_         


        
相关标签:
2条回答
  • 2021-01-27 13:05

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

    0 讨论(0)
  • 2021-01-27 13:13

    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)
    
    0 讨论(0)
提交回复
热议问题