Rename multiple directories

10,368

Solution 1

find . -depth -type d -name doc -exec sh -c 'mv "${0}" "${0%/doc}/Doc"' {} \;

Solution 2

In zsh, you can use the zmv function to mass-rename files:

zmv '(**/)doc' '${1}Doc'

If you have non-directories called doc, make sure not to match them by adding a glob qualifier:

zmv -Q '(**/)doc(/)' '${1}Doc'

Solution 3

If your intention is to capitalize the directory and you're using bash 4+ this should do:

find . -type d -name doc -print0 \
| while read -rd $'\0' file; do
    dname=$(dirname "$file")
    fname=$(basename "$file")
    mv "$file" "$dname"/"${fname^}"
  done

Note the use of \0 to ensure the correct handling of unusual filenames.

Update

As jw013 points out in the comments ${var^} doesn't work as I expected. I've amended the answer to separate the path into directory and filename and apply the ^ operator only to $fname.

Btw, thanks rush for adding the missing pipe.

Share:
10,368

Related videos on Youtube

Marc
Author by

Marc

delete me

Updated on September 18, 2022

Comments

  • Marc
    Marc almost 2 years

    I want to find all directories with the last subdirectory named doc, for then rename them to Doc. How can be renamed?

    I've the first part:

    find -type d -name 'doc' 
    

    which returns directories paths like:

    ./foo/bar/doc
    
    • Marc
      Marc almost 12 years
      What about to use command rename? In flag -exec
    • jw013
      jw013 almost 12 years
      If rename works for you by all means use it. The trouble is there is no standard rename(1) command, so unless you tell everyone your version of rename we can't really help you with that approach.
  • jw013
    jw013 almost 12 years
    I don't think ${var^} expansion does what you want it to. var=./foo/bar/doc; echo ${var^} gives ./foo/bar/doc. The ^ expansion only affects the first character.
  • Thor
    Thor almost 12 years
    @jw013: You're right, I've amended the answer.
  • mzet
    mzet almost 12 years
    (Sorry for the above). Unfortunately your solution doesn't work for following directory structure: mkdir -p dir1/doc/dir2. In this case even though doc directory isn't the last subdirectory (Marc's requirement) it is renamed.
  • Thor
    Thor almost 12 years
    Well the OP didn't specify any other selection criteria besides -name doc, but if only leaf directories should be matched a check that $dir only contains . and .. subdirectories could be done.