2

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" {} \;

  • What error are you getting? – Edward Falk Jul 26 '16 at 17:08
2

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
' _ {} +
  • Thanks for the answer, sorry i did not understand how for .. do is working here. -depth works for any number of depth? and is it working like this for dir1/dir2/dir3... 1. Go through files in dir1 then dir1, 2. Go through files in dir2 then dir2. and so on... – Syed Mudabbir Feb 25 '16 at 23:26
  • @SyedMudabbir Yes, -depth means to go through dir2 before dir1, and dir3 before dir2, etc. – Gilles Feb 25 '16 at 23:28
1

Usual zsh answer to this kind of question:

autoload zmv # best in ~/.zshrc
zmv -v '(**/)(* *)' '$1${2// /-}'

It takes care of processing the files depth-first, and checks for conflicts or overwrites (regular files only) better than you'd usually do by hand.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.