Copy nested folders contents to one folder recursively (terminal)

32,182

Solution 1

This will copy all *.jpg files from the current folder to a new folder and preserve the directory structure.

tar cvfp `find . -name "*.jpg"` | (cd <newfolder>; tar xfp -)

To copy without preserving the directory structure:

cp `find . -name "*.jpg"` <newfolder>

Solution 2

Off the top of my head:

find . -type f -name \*.jpg -exec cp \{\} $TARGETFOLDER \;

If that doesn't work, comment and I'll try again, but find is definitely the way to go.

Share:
32,182

Related videos on Youtube

Wolfr
Author by

Wolfr

Interface designer looking for the balance between aesthetics and usability. Also working in the frontend trenches during development.

Updated on July 09, 2022

Comments

  • Wolfr
    Wolfr almost 2 years

    I have a Wordpress upload folder that is structured using subfolders for months.

    wolfr2:uploads wolfr$ tree .
    .
    |-- 2007
    |   |-- 08
    |   |   |-- beautifulkatamari.jpg
    |   |   |-- beautifulkatamari.thumbnail.jpg
    |   |   |-- beetle.jpg
    |   |   |-- beetle.thumbnail.jpg
    

    How do I use terminal to copy all the images recursively into another folder? I can't seem to wildcard folders like you can wildcard filenames. (e.g. *.jpg or *) (I'm on Mac OSX)

    cp -R ./*.jpg .
    

    ?

  • Wolfr
    Wolfr over 14 years
    I should have carlified in the OP that I want to get rid of the structure and just want all the images in a flat folder.
  • Richard Pennington
    Richard Pennington over 14 years
    Darn, my backquotes around the find were left off.
  • Foxocube
    Foxocube over 9 years
    This doesn't appear to work for files with spaces in their name
  • Sinatra
    Sinatra about 9 years
    This is the correct answer because it works with files / folders that have spaces in their names.