Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I move just the files with a particular extension from nested sub-directories?

Tags:

bash

In a directory I have many sub-directories and each of these sub-directories have many files of different types. I want to extract all the files with a particular extension from each subdirectory and put it in a different folder. Is it possible to write a bash script to do this? If so how?

like image 514
lovespeed Avatar asked Nov 30 '22 05:11

lovespeed


2 Answers

$ find <directory> -name '*.foo' -exec mv '{}' <other_directory> \;

find does a recursive search through a directory structure and performs the given actions on any files it finds that match the search criteria.

In this case, -name '*.foo' is the search criteria, and -exec mv '{}' <other_directory> \; tells find to execute mv on any files it finds, where '{}' is converted to the filename and \; represents the end of the command.

like image 144
vergenzt Avatar answered Dec 06 '22 07:12

vergenzt


If you have bash v4 and have

shopt -s globstar

in your .profile, you can use:

mv ./sourcedir/**/*.ext ./targetdir
like image 30
novacik Avatar answered Dec 06 '22 09:12

novacik