Dean
Dean

Reputation: 763

Moving files/directories older than 7 days

I have this code to find files/directories older than 7 days, then execute a mv. However I realise I need a different command for directories and files. -type also does not support fd - a manual says it only supports one character.

find /mnt/third/bt/uploads/ -type f -mtime +7 -exec mv {} /mnt/third/bt/tmp/ \;

How do I move both files and directories >7d into /mnt/third/bt/tmp/ whilst keeping the same structure they had in /mnt/third/bt/uploads/?

Thanks

Upvotes: 3

Views: 14031

Answers (2)

clt60
clt60

Reputation: 63922

IMHO, this is a non-trivial problem to do it correctly - at least for me :). I will be happy, if someone more experienced post a better solution.

The script: (must have a GNU find, if your "find" is GNU-version change the gfind to find)

FROMDIR="/mnt/third/bt/uploads"
TODIR="/mnt/third/bt/tmp"
tmp="/tmp/movelist.$$"

cd "$FROMDIR"
gfind . -depth -mtime +7 -printf "%Y %p\n" >$tmp
sed 's/^. //' < $tmp | cpio --quiet -pdm "$TODIR"

while read -r type name
do
    case $type in
    f) rm "$name";;
    d) rmdir "$name";;
    esac
done < $tmp
#rm $tmp

Explanation:

  • find everything what you want move (will copy first and delete after) and store it in a tmpfile (find)
  • copy a list of things from a tmpfile to the new place (cpio)
  • and finally remove old files and dirs - based on a list from a tmpfile (while...)

The script does not handling symbolic links, fifo files, etc., and will print zilion errors at the deleting directories what are old, but they're not empty (contain new files or subdirs)

DRY RUN first! :)

Upvotes: 2

pyvi
pyvi

Reputation: 675

If you want to search for both files and directories, find supports boolean operators.

Upvotes: 1

Related Questions