Search code examples
linuxrecursionmove

Linux find all files in sub directories and move them


I have a Linux-System where some users put files with ftp in a Directory. In this Directory there are sub-directories which the users can create. Now I need a script that searches for all files in those subdirectories and moves them in a single Directory (for backup). The Problem: The Sub directories shouldn´t be removed.

the directory for the users is /files/media/documents/ and the files have to be moved in the Directory /files/dump/. I don´t care about files in /files/media/documents/, they are already handled by another script.

I already tried this script:

for dir in /files/media/documents/
do
    find "$dir/" -iname '*' -print0 | xargs -0 mv -t /files/dump/
done

Solution

  • Instead of iterating, you could just use find. In man-page there is a "-type" option documented, so for moving only files you could do:

    find "/files/media/documents/" -type f -print0 | xargs -0 mv -t /files/dump/
    

    You also won't like to find files in /files/media/documents/, but all sub-directories? Simply add "-mindepth":

    find "/files/media/documents/" -type f -mindepth 1 -print0 | xargs -0 mv -t /files/dump/
    

    Alternatively you could also use "-exec" to skip a second command (xargs):

    find "/files/media/documents/" -type f -mindepth 1 -exec mv {} /files/dump/ \;