Page 1 of 1

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!

Linux/macOS - How t...
Clear all

Linux/macOS - How to split a directory into multiple directories

1 Posts
1 Users
Famed Member Admin
Joined: 10 years ago
Posts: 2556
Topic starter  

The problem I ran into was that I had several thousand of files in one directory, and I wanted them to be divided over multiple subdirectories so my file explorer wouldn't go bonkers (long story).

So basically: one dir has thousands of files -> one dir has several sub dirs with a fixed number of files in it (50 in this example).

For this I wrote a Terminal script, which may be helpful to others:


# dirnumber generates the name of the output directory

# base directory

# the number of files we have moved

# number of files per dir

# Go through all JPG files in the current directory
for f in *; do

   # Create new output directory if first of new batch of 2000
   if [ $filesmoved -eq 0 ]; then
      mkdir $outdir
   # Move the file to the new subdirectory
   mv "$f" "$outdir"
   # You can try this instead of the "mv" line to do testing
   # echo "$f" "$outdir"

   # Count how many we have moved to there

   # Start a new output directory if we have sent "filesindir"
   [ $filesmoved -eq filesindir ] && filesmoved=0


Like what you see and you'd like to help out? 

The best way to help is of course by assisting others with their questions here in the forum, but you can also help us out in other ways:

- Do your shopping at Amazon, it will not cost you anything extra but may generate a small commission for us,
- send a cup of coffee through PayPal ($5, $10, $20, or custom amount),
- become a Patreon,
- donate BitCoin (BTC), or BitCoinCash (BCH).