Unix command for recursively copying files

2

I need a unix command for the following:

Directory Structure

/project
    /images
        /products
            /cup.jpg
            /laptop.jpg
        /designs
            /alpha.jpg
            /beta.jpg
            /gamma.jpg
        /team
            /jeff.jpg
        /locations
            /new-york.jpg

I would like one command to copy all files* not folders out of the "images" directory recursively to something like this.

/assets
    /cup.jpg
    /laptop.jpg
    /alpha.jpg
    /beta.jpg
    /gamma.jpg
    /jeff.jpg
    /new-york.jpg       

I tried this but it just copied the folders recursively cp -r ./project/images/* ./assets/

ThomasReggi

Posted 2013-04-23T17:43:03.530

Reputation: 443

4I just found this and it works find project -type f -exec cp {} assets \; – ThomasReggi – 2013-04-23T17:45:00.430

Please post your solution as an answer. Answering your own questions is not only accepted but encouraged. I would recommend, however, that you quote {} so you won't have trouble with file names with spaces: find project/images -type f -exec cp '{}' assets \;

– terdon – 2013-04-23T21:25:38.607

@terdon {} does not have to be quoted.

– Lri – 2013-04-24T00:27:02.810

Answers

6

This executes cp for every file, so it can be noticeably slower if there are many small files (but not with typical images):

find project -name \*.jpg -exec cp {} assets \;

This takes multiple arguments at a time:

find project -name \*.jpg -print0 | xargs -0 -I% cp % assets

Without -0 filenames that contain single quotes or double quotes would result in an error like xargs: unterminated quote.

Bash 4 supports ** with shopt -s globstar:

cp project/**/*.jpg assets

Lri

Posted 2013-04-23T17:43:03.530

Reputation: 34 501