user10701455
user10701455

Reputation: 35

Bash script to move all png files in folder and its subfolders to another directory?

In ~/Desktop/a/ , I have .png files, and there are also subfolders within this that also have .png files.

I'd like to move all of those .png files to another folder.

This is my code so far. It runs, but nothing is placed into the target folder. What is the problem?

#!/bin/bash
cd ~/Desktop/a/
for f in $(find . -type f -name "*.png")
do 
    mv $f ~/Desktop/new/
done

Upvotes: 3

Views: 4626

Answers (2)

melpomene
melpomene

Reputation: 85767

If your bash is new enough, you can also use globstar:

cd ~/Desktop/a || exit 1
shopt -s globstar
mv -- **/*.png ~/Desktop/new

Or (if there are too many files to fit in a single command line):

shopt -s globstar
for f in ~/Desktop/a/**/*.png; do
    mv -- "$f" ~/Desktop/new
done

Upvotes: 0

Feng
Feng

Reputation: 4038

I guess that these image filenames maybe include spaces or other special characters.

find ~/Desktop/a/ -type f -name "*.png" -exec mv "{}" ~/Desktop/new/ \;

or

find ~/Desktop/a/ -type f -name "*.png" -print0 | xargs -0 -I{} mv "{}" ~/Desktop/new/

Upvotes: 5

Related Questions