How to move files out of subdirectories with given extension recursively to a destination-folder? [duplicate]

I want to move all the *.txt files from all the subdirectories located in a given directory to one destination-directory.

When doing it as below, it moves EVERY file - how can I reduce it to all the *.txt files only?

find -type f -print0|xargs -0r mv -it "/path to my folder/destination-directory"

Solution 1:

Use a glob pattern with -name option of find to indicate the desired pattern, *.txt in your case:

find . -type f -name '*.txt' -exec mv -t /destination {} +

Of course, replace /destination with the actual destination directory.

Notes:

  • You don't need to spawn xargs and an anonymous pipe, use the mv logic within the -exec predicate of find

  • find ... -exec handles all kind of possible filenames and ARG_MAX as well

  • GNU mv (default in Ubuntu) has -t to take a destination directory, so that you can leverage the + argument of -exec to send all files in single run of mv (or at least minimal runs if ARG_MAX is triggered in the process)

Solution 2:

Add a -name test

find -type f -name "*.txt" -print0 |...

Don't forget to quote the glob to prevent shell expansions.

For case-insensitive search, use -iname instead of -name

Solution 3:

find /folder/ -type f -name "*.txt" -exec mv {} /other/folder/ \;

I tested this, works nicely.