Bash: Copy files by extension from sub-directories to another directory

Goal: Copy all image (*.png) files from all sub-directories of dir1 into single directory, dir2.

Source:

bash_examples/
dir1
 - dir3
    - f1.png
    - f2.png
    - f5.jpg
 - dir4
    - f3.png
    - f4.png

Destination:

bash_examples/
dir2
 - f1.png
 - f2.png
 - f3.png
 - f4.png


1. Change the directory to dir1

cd ~/Desktop/bash_examples/dir1/

2. Find all files with .png extension then apply cp command to copy each file from dir1 to dir2

find . -name \*.png -exec cp -v '{}' "/Users/mac0611/Desktop/bash_examples/dir2" ";"
./dir3/f1.png -> /Users/mac0611/Desktop/bash_examples/dir2/f1.png
./dir3/f2.png -> /Users/mac0611/Desktop/bash_examples/dir2/f2.png
./dir4/f3.png -> /Users/mac0611/Desktop/bash_examples/dir2/f3.png
./dir4/f4.png -> /Users/mac0611/Desktop/bash_examples/dir2/f4.png

cd ..; ls dir2/

f1.png    f2.png    f3.png    f4.png

Comments