Home > front end >  Use find to copy files to a new folder
Use find to copy files to a new folder

Time:12-27

I'm searching for a find command to copy all wallpaper files that look like this:

3245x2324.png (All Numbers are just a placeholder) 3242x3242.jpg

I'm in my /usr/share/wallpapers folder and there are many sub folders with the files I want to copy. There are many like "screenshot.png" and these files I don't want to copy.

My find command is like this:

find . -type f -name "*????x????.???"

If I search with this I get the files I wanted to see, but if I combine this with -exec cp:

find . -type f -name "*????x????.???" -exec cp "{}" /home/mine/Pictures/WP \;

the find command only copies 10 files and there are 77 (I counted with wc).

Does anyone know what I'm doing wrong?

CodePudding user response:

You can look it up if you follow the link. renaming with find You can use -exec to do this. But i'm not sure you can do rename and copy in one take.Maybe with a script that got executed after every find result.

But that's only a suggestion.

CodePudding user response:

One idea/approach is to copy absolute path of the file in question to the destination, but replace the / with an underscore _ since / is not allowed in file names, at least in a Unix like environment.

With find and bash, Something like.


find /usr/share/wallpapers -type f -name "*????x????.???" -exec bash -c '
   destination=/home/mine/Pictures/WP/
   shift
   for f; do
     path_name=${f%/*}
     file_name=${f##*/}
     echo cp -vi "$f" "$destination${path_name//\//_}$file_name"
   done' _ {}  


With globstar nullglob shell option and Associative array from the bash shell to avoid the duplicate filenames.

#!/usr/bin/env bash

shopt -s globstar nullglob
pics=(/usr/share/wallpapers/**/????x????.???)
shopt -u globstar nullglob

declare -A dups
destination=/home/mine/Pictures/WP/

for i in "${pics[@]}"; do
  ((!dups["${i##*/}"]  )) &&
  echo cp -vi "$i"  "$destination"
done

  • GNU cp(1) has the -u flag/option which might come in handy along the way.
  • Remove the echo if you're satisfied with the result.
  • Related