Search code examples
shell

shell script for listing all images in current and subfolder and copy them into one folder?


I have some folder hierarchy, in some of the folders there are images, I need a shell script which can list all images and copy them into one specified folder, where listing them is not important, I just want to copy all images into a folder?

I know I can

ls -R *.png

but how do I copy them all to one folder?

Thanks!


Solution

  • Update: As glenn jackman has pointed out, this would be slightly more efficient to use over the answer I provided:

    find . -type f -name \*.png | xargs cp -t destination
    

    For the explanation, see glenn's comments that follow this answer.


    One way is to use find:

    find . -type f -name "*.png" -exec cp {} ~/path/to/your/destination/folder \;
    

    Explanation:

    • find is used to find files / directories
    • . start finding from the current working directory (alternatively, you can specify a path)
    • -type f: only consider files (as opposed to directories)
    • -name "*.png": only consider those with png extension
    • -exec: for each such result found, do something (see below)
    • cp {} ~/path/to/your/destination/folder \;: this is the do something part: copy each such result found (substituted into the {}) to the destination specified.