Move images from sub-folders into new sub-folders

I have a folder composed of M several sub-folders, each of them containing some text files and N images (*.png)

This is what the tree looks like:

/parent/ /sub-folder1/ /data1.dat /data2.dat /image1.png /image2.png ... /imageN.png /sub-folder2/ /data1.dat /data2.dat /image1.png /image2.png ... /imageN.png ... /sub-folderM/ /data1.dat /data2.dat /image1.png /image2.png ... /imageN.png

notice that all images in each sub-folder are named the same (ie: image1.png, ..., imageN.png)

What I need is to move only the images into a new parent folder (say parent2), while replicating the sub-folder structure. After the moving is done the new parent folder should look like this:

/parent2/ /sub-folder1/ /image1.png /image2.png ... /imageN.png /sub-folder2/ /image1.png /image2.png ... /imageN.png ... /sub-folderM/ /image1.png /image2.png ... /imageN.png

(ie: only images and respecting the same sub-folders structure)

and the original parent folder should look like:

/parent/ /sub-folder1/ /data1.dat /data2.dat /sub-folder2/ /data1.dat /data2.dat ... /sub-folderM/ /data1.dat /data2.dat

(ie: images moved out)

I've seen some examples of scripts that can move all filed into a new folder (Shell script to move all files from subfolders to parent folder) or some that can move only images (Script to move pictures) but I haven't found one that would do so while respecting the sub-folders tree.

2 Answers

You can try using rsync:

rsync -av --include="*/" --include='*.png' --exclude='*' parent1 parent2

this creates directory parent2 and copies all files with .png extension with subdirectory structure to it.
explanation

  • -v verbose to see whats copied
  • -a archive mode (copy subdirectories with same ownership, permissions etc.)
  • --include '*/' --include='*.png' include .png ending files first part is to create subdirectories
  • --exclude='*' exclude all other files for more info see rsync man page
  1. Copy parent1 to parent2
  2. Remove dat files from parent2 subdirectories
  3. Remove png files from parent1 subdirectories
$ cp -r parent1/ parent2
$ rm parent2/*/*.dat
$ rm parent1/*/*.png

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like