6

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
2
  • 1
    What about to use command rename? In flag -exec
    – Marc
    Jul 25, 2012 at 11:04
  • 1
    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
    Jul 25, 2012 at 13:27

3 Answers 3

7
find . -depth -type d -name doc -exec sh -c 'mv "${0}" "${0%/doc}/Doc"' {} \;
0
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'
1

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.

5
  • 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.
    – jw013
    Jul 25, 2012 at 12:51
  • @jw013: You're right, I've amended the answer.
    – Thor
    Jul 25, 2012 at 13:22
  • . ├── cos │ └── doc ├── doc └── tt └── doc └── kk
    – mzet
    Jul 25, 2012 at 14:20
  • (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.
    – mzet
    Jul 25, 2012 at 14:31
  • 1
    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.
    – Thor
    Jul 25, 2012 at 14:48

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .