How can I iterate through a folder and move/copy every Nth item

I want to make a time lapse from a folder of images, but there are too many and the time lapse progresses to slowly. How do I select, for example, every 10th item, and either copy or move the items into a separate folder?


The quickest way is to use bash and awk syntax in your Terminal.app

for file in `find /SOURCE/DIR -type f | awk 'NR %10 == 0'`; do echo mv $file /DEST/DIR ; done

for statement introduces the bash loop, to iterate through a set of data where file is the variable.

find parses the /SOURCE/DIR for that which is specified.

| acts as a pipe, passing stout from find back to stdin

awk interprets stdin and prints only lines meeting the conditions specified by 'NR %10 == 0’

  • NR is an awk built-in variable that specifies the record/line number to be evaluated.

  • % is a numerical operator telling awk that the following character(s) must be treated as such.

  • == is relational operator for must be equal to..

  • 0 is the binary expression for TRUE

So, that’s all fancy for "find every 10th file that exists in this directory and output it;

  • do introduces the action to perform on the output.
  • echo is used to double check the command, the results of which will be printed to stout. If all looks well, remove it and perform the action (mv, cp)
  • mv is a built in bash command to take one file and move(or rename it).
  • cp is another built in bash command to mv one file from one dir. to another while preserving the original. You can directly substitute cp for mv if you wish to preserve the contents of the original directory.
  • $file references the file variable that has now been defined.

So, that’s all fancy for tell me what happens when I…(echo) “move (or, copy) all the files specified by the previous parameters to this other directory;”

  • done

That’s all fancy for telling bash to terminate the loop since you’re done :)