Preserve directory structure when moving files using find
I know find
was specified, but this sounds like a job for rsync
.
I most often use the following:
rsync -axuv --delete-after --progress Source/ Target/
Here is a good example if you want to only move files of a particular file-type (example):
rsync -rv --include '*/' --include '*.js' --exclude '*' --prune-empty-dirs Source/ Target/
Instead of running mv /home/ketan/hex/foo /home/maxi
, you'll need to vary the target directory based on the path produced by find
. This is easier if you change to the source directory first and run find .
. Now you can merely prepend the destination directory to each item produced by find
. You'll need to run a shell in the find … -exec
command to perform the concatenation, and to create the target directory if necessary.
destination=$(cd -- "$destination" && pwd) # make it an absolute path
cd -- "$source" &&
find . -type f -mtime "-$days" -exec sh -c '
mkdir -p "$0/${1%/*}"
mv "$1" "$0/$1"
' "$destination" {} \;
Note that to avoid quoting issues if $destination
contains special characters, you can't just substitute it inside the shell script. You can export it to the environment so that it reaches the inner shell, or you can pass it as an argument (that's what I did). You might save a bit of execution time by grouping sh
calls:
destination=$(cd -- "$destination" && pwd) # make it an absolute path
cd -- "$source" &&
find . -type f -mtime "-$days" -exec sh -c '
for x do
mkdir -p "$0/${x%/*}"
mv "$x" "$0/$x"
done
' "$destination" {} +
Alternatively, in zsh, you can use the zmv
function, and the .
and m
glob qualifiers to only match regular files in the right date range. You'll need to pass an alternate mv
function that first creates the target directory if necessary.
autoload -U zmv
mkdir_mv () {
mkdir -p -- $3:h
mv -- $2 $3
}
zmv -Qw -p mkdir_mv $source/'**/*(.m-'$days')' '$destination/$1$2'
you could do it using two instances of find(1)
There's always cpio(1)
(cd "$soure" && find … | cpio -pdVmu "$destination")
Check the arguments for cpio. The ones I gave