1

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?

6
  • 1
    What are the names of the PDF files?
    – dr_
    Commented Jul 13, 2017 at 11:25
  • Something like 453041477-18100305.pdf. The second number changes.
    – Til Hund
    Commented Jul 13, 2017 at 11:26
  • 1
    And how are these 100 PDFs to be chosen? At random, by name, creation date, etc. ?
    – dr_
    Commented Jul 13, 2017 at 11:28
  • By name. Sorry, I missed that part in my original question.
    – Til Hund
    Commented Jul 13, 2017 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_
    Commented Jul 13, 2017 at 11:36

2 Answers 2

1

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
c=1
while (($#)); do
  mkdir ${c}
  if [ $# -ge 100 ]; then
    mv -- "${@:1:100}" ${c}
    c=$((c+1))
    shift 100
  else
    mv -- "${@}" ${c}
    shift $#
  fi
done
1
  • Thank you, don_crissti. This script did exactly what I was looking for.
    – Til Hund
    Commented Jul 13, 2017 at 22:34
1

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

#!/bin/bash

DEFAULT_DELIM_SIZE=100
num_of_total_file=$(ls | grep "pdf" | wc -l)
num_of_total_folder=$((num_of_total_file/DEFAULT_DELIM_SIZE))

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
    fi
done

# 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
    fi
done
1
  • 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
    Commented Jul 13, 2017 at 19:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .