Centos – Renaming Files and Directories Recursively using rename/find

centosfindlinuxrename

I started learning linux on vmware using centos 7. I created an image directory and several layers of files and sub-directories in that folder. most of the names containing spaces. I want to use a single command to rename all the files and directories at once.

command i am using right now is

find . -type f -exec rename "find" "replace" {} \;
&
find . -type d -exec rename "find" "replace" {} \;

Where as find is a space and replace is "-"(hiphen). I even tried below command looking at one of the answer in stack exchange.

find . -iname "find" -exec rename "find" "replace" {} \;

Best Answer

Since you're going to rename directories under find's nose, tell it to act on the content of a directory before the directory itself, with -depth. On the other hand, doing directories separately from regular files doesn't help.

To rename a file with the tools that are available on a default CentOS installation, you can use a shell and mv. Take care to change only the base name, not the directory name (since the new directory doesn't exist yet).

find . -depth -exec bash -c '
  for filename do
    basename=${filename##*/}
    mv "$filename" "${filename%/*}/${basename// /-}"
  done
' _ {} +
Related Question