Sunday, 13 May 2012

Copy files in order using Linux or OS X


How do I copy files in sorted order using the Linux or OS X Terminal?


In the terminal, you can use a combination of the "find", "sort", "xargs", and "cp" commands to copy files in sorted order.

For instance, first switch to the directory that has the files you would like to copy:

cd /path/to/media/directory

Then copy the files in sorted order:

find . -print0 | sort -z | xargs -0 cp --parents
  --target-directory=/path/to/destination -v

Note that the above command is a single line, (but it appears split into two in order to fit into this page.)

In the cp command, the -v flag will help you see if files are being copied in the desired order. This can be omitted if you do not wish to monitor the files being copied. To customize the order of your sort, simply customize the flags used with the 'sort' command (see the manual pages for 'sort' using the command 'man sort', if you're unsure of how to do this).

Why copying files in sorted order can be useful:

Some MP3 players, digital media players, and other devices play back media in the order that files were copied to it. With some file managers, files can be copied out of order, in reverse-sorted order, or in other ways that copy files out of the order that is desired (such as copying multiple files in parallel). There are also other situations where copying files in a particular sorted order would be useful. For instance, copying files in some required order to a custom-built robot's flash memory, etc.

Other thoughts:

Although the command 'cp -R' can also recursively copy things in order, the method mentioned above in this post should give a bit more flexibility customizing the sorted order of the copied files.

No comments:

Post a Comment