3

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
user10701455
  • 35
  • 1
  • 3
  • 2
    This might help: [How to debug a bash script?](http://unix.stackexchange.com/q/155551/74329) – Cyrus Nov 25 '18 at 08:25
  • See: [Copy every file of entire directory structure into base path of another](https://stackoverflow.com/q/9800989/3776858) – Cyrus Nov 25 '18 at 08:28
  • I do not see why this script should fail silently. But in any case I would enclose `$f` in double quotes. You may want to try `echo` instead of `mv`. – tif Nov 25 '18 at 08:30
  • `for f in $(find ...)` is basically a bug. See https://mywiki.wooledge.org/BashPitfalls#for_f_in_.24.28ls_.2A.mp3.29. – melpomene Nov 25 '18 at 08:32

2 Answers2

5

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/
Feng
  • 3,592
  • 2
  • 15
  • 14
1

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
melpomene
  • 84,125
  • 8
  • 85
  • 148