How would I go about writing a script to loop through every folder on a hard drive, find any video files, extract them to the root of the hard drive, and then delete everything else?

  • Use find, and in particular its -exec switch. Match file names via -iregex or -iname. – Daniel Andersson Feb 9 '13 at 15:04

Typically, if you need to "loop" over a set of files in Linux, you don't want to write an actual Bash loop (e.g. with for), but use find instead. The following should work for all versions of find, and Linux distributions come with GNU find, whose manual you should definitely read at some point.

Be careful with the following commands. If you don't know what you're doing or don't check the results first, you could irreversibly lose data.

find /mount/drive -type f  \( -iname "*.mp4" -o -iname "*.avi" \) \
-exec echo mv '{}' /mount/drive/ \;

This would print a list of mv commands. Once you're sure it does what you want, remove the echo from the command and execute it again.


  • -type f will restrict the results to only files.
  • find will overwrite files with the same name without a warning. To avoid collisions, use mv -i, which would prompt you in such a case.
  • You can add more conditions to this to search for other file types, e.g. -o -iname "*.mov" et cetera.

In a second step, we will delete everything that's not in the root of the drive. To do so, we need two commands, since you first want to delete all the files …

find /mount/drive -mindepth 2 -type f

Once you're sure this lists everything you want to delete, add -delete to the command. Here, mindepth 2 ensures that your root (with all the videos in it) stays untouched.

Then, find the remaining empty folders:

find /mount/drive -mindepth 1 -depth -type d -empty

Similar to above, add -delete to this command to actually delete the empty directories.

| improve this answer | |
  • Fantastic answer, the best I've ever gotten on StackExchange. Thanks so much. – Conor Taylor Feb 9 '13 at 16:38
  • This'll find folders named '...avi' as well IIRC. Also, will this work with 2+ files found? IIRC we discussed this recently with arguments after {}. – Daniel Beck Feb 9 '13 at 16:42
  • @Daniel Thanks, you're right. the -type f applies to both only if you group the conditions. With regard to moving and multiple arguments, etc., it only works with GNU find (and GNU Coreutils mv), but find … -exec mv -t /mount/drive '{}' \+ should do the trick. – slhck Feb 9 '13 at 16:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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