4

Sometimes I have a folder full of jpg's and I need to randomly choose 8 or so of them. How could I automate this so my account randomly chooses 8 jpg's from the folder and copies them to another destination?

My question is simple really, instead of using cp and giving it a file name then destination file name, I want to build a script that randomly chooses 8 of the .jpgs in the folder, and copies those to another folder.

  • you can use a combination of crontab and mv. – vfbsilva Jul 22 '15 at 19:55
13

You could use shuf:

shuf -zn8 -e *.jpg | xargs -0 cp -vt target/
  • shuf shuffles the list of *.jpg files in the current directory.
  • -z is to zero-terminate each line, so that files with special characters are treated correctly.
  • -n8 exits shuf after 8 files.
  • xargs -0 reads the input delimited by a null character (from shuf -z) and runs cp.
  • -v is to print every copy verbosely.
  • -t is to specify the target directory.
1

You could retrieve files in this way:

files=(/tmp/*.jpg)
n=${#files[@]}
file_to_retrieve="${files[RANDOM % n]}"
cp $file_to_retrieve <destination>

make a loop 8 times.

  • So essentially rather than an answer you provide a list of variable names. – gented Dec 18 '18 at 22:35
1

The best answer absolutely didn't worked for me, because -e *.jpg doesn't actually look into the working directory. It's just an expression. So shuf doesn't shuffle anything...

I found the following improvement based on what I learned in that post.

find /some/dir/ -type f -name "*.jpg" -print0 | xargs -0 shuf -e -n 8 -z | xargs -0 cp -vt /target/dir/
  • The -e *.jpg expects a set of matching files in the current directory. If there are no matches it will (usually) return the single literal *.jpg to shuf, which then has only one element to consider. – roaima Dec 17 '17 at 13:58

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.