EMC
EMC

Reputation: 1903

How do I move folders recursively?

I'm trying to do something like this to remove spaces from all directories and sub-directories. Here is the code I have;

find /var/www/ -name "*" -type d | while read dir; do
  mv "$dir" `echo "$dir" | tr ' ' '.'`;
done

This works but only per each directory at one time. It does not work on sub-directories, unless I re-run the script multiple times. If you guys know a better way of doing this so it will work on sub-directories too, please let me know.

Between, when I run this script it turns directory such as "This is directory one" for example into "This.is.directory.one". But sub-directories with spaced folder names does not change unless I re-run the script multiple times like I said.

Upvotes: 2

Views: 3490

Answers (4)

Dennis Williamson
Dennis Williamson

Reputation: 359925

Similar to Sorpigal's answer, but slightly simpler due to the use of -execdir:

find . -depth -mindepth 1 -type d -name "* *" -execdir bash -c 'old="{}"; new=${old// /.}; mv "${old##*/}" "$new"' \;

Upvotes: 1

Hamdan
Hamdan

Reputation: 1

find ~/my/path -type f -name "*(J)*.*" -exec mv {} ~/my/path/j \;

from https://superuser.com/questions/103151/recursive-move-files-of-specific-type-to-a-specific-path

Upvotes: 0

sorpigal
sorpigal

Reputation: 26086

This ought to work correctly.

find . -depth -type d -name '* *' -exec bash -c 'dir="${1%%/}";d1="${dir%/*}";d2="${dir##*/}";mv "$1" "$d1/${d2// /.}"' -- {} \;

We're doing depth-first searching, meaning that directory contents get processed before the directory they're in. We're including only directories with spaces in the name. Then we have a little bash routine which, using parameter substitution, chops the trailing slash off of the path, splits the path in to two parts (the directory name (d2) and the path to that directory (d1)), then mv's the original full path and name to the same path but with spaces in the name replaced by a periods.

Upvotes: 1

Eir Nym
Eir Nym

Reputation: 1579

you should put "depth" flag for your find command: it causes find(1) to perform a depth first traversal. In FreeBSD it is -d. Sorry, I don't remember name for same in Linux distributions, check find(1) for details.

find -d $dir -type d|  while read dir; do
  mv "$dir" `echo "$dir" | tr ' ' '.'`;
done

Upvotes: 0

Related Questions