hzxu
hzxu

Reputation: 5823

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!

Upvotes: 2

Views: 6541

Answers (2)

sampson-chen
sampson-chen

Reputation: 47267

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.

Upvotes: 6

Harish Karthick
Harish Karthick

Reputation: 720

To copy multiple file patterns in single go we can use -regex instead -name

find . -type f -regex '.*\(jpg\|jpeg\|png\|gif\|mp4\|avi\|svg\|mp3\|vob\)' -exec cp {} /path/to/your/destination/folder \;

Upvotes: 2

Related Questions