I have one folder with 2000 PDF files on a Mac. Using the command line, I would like to move each 100 PDFs to another folder to be created in the same directory. So that I would have 20 folders (named 1, 2, etc.) each containing 100 PDFs in the main directory. How can I achieve that?

  • 1
    What are the names of the PDF files? – dr_ Jul 13 '17 at 11:25
  • Something like 453041477-18100305.pdf. The second number changes. – Til Hund Jul 13 '17 at 11:26
  • 1
    And how are these 100 PDFs to be chosen? At random, by name, creation date, etc. ? – dr_ Jul 13 '17 at 11:28
  • By name. Sorry, I missed that part in my original question. – Til Hund Jul 13 '17 at 11:29
  • 1
    So, their filename is 453041477-<n>.pdf and you want to put them in numerical order by n, then move each subsequent group of 100 in a different directory? – dr_ Jul 13 '17 at 11:36

You could use set, process batches of 100 files via "${@:START:COUNT}" (range of positional parameters) and shift 100 while incrementing a counter c to create the directories:

set -- *.pdf
while (($#)); do
  mkdir ${c}
  if [ $# -ge 100 ]; then
    mv -- "${@:1:100}" ${c}
    shift 100
    mv -- "${@}" ${c}
    shift $#
| improve this answer | |
  • Thank you, don_crissti. This script did exactly what I was looking for. – Til Hund Jul 13 '17 at 22:34

I have just written below bash script for your specific problem. This may help you.


num_of_total_file=$(ls | grep "pdf" | wc -l)

echo "Total number of pdf files = $num_of_total_file"
echo "Total number of folder will generated if not exist $num_of_total_folder"

# create directories if not exist
for (( i = 0; i < $num_of_total_folder; i++ )); do
    if [[ ! -d $i ]]; then
        mkdir $i

# file name format should be like this <arbitrary_numb>-<folder_num>.pdf
for file in *.pdf; do
    prefix=$(echo $file | awk '{split($0, a, "-"); print a[2]}' | awk '{split($0, a, "."); print a[1]}')
    if [[ -d $prefix ]]; then
        mv $file $prefix
| improve this answer | |
  • Thank you very much for posting, Talayhan. I looks good. However, it does not move any PDF to the newly created folders. The result of running your script is that it creates to me a folder 0 and folder 1 (when testing it with exactly 200 PDF), but all PDF are still in the main directory. The might be something not quite there yet with the last part of the script. Note that the correct result for the given test should be that folder 0 and folder 1 have each 100 PDF. Folder 0 the first 100, folder 1 the last 100 PDF. – Til Hund Jul 13 '17 at 19:07

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.