9

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"
1
  • try: find . -type f -name "*.txt" -print0|xargs -0r mv -it "/path to my folder/destination-directory" Feb 27 '17 at 15:56
11

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)

6

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

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

I tested this, works nicely.

2

Using your original command:

find . -type f -name "*.txt" -print0|xargs -0r mv -it /path/to/destination

Info:

  1. .: search in current location

  2. "*.txt": files that have a .txt extension in their names

Not the answer you're looking for? Browse other questions tagged or ask your own question.