Page 1 of 1
Forum

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...
 
Share:
Notifications
Clear all

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

1 Posts
1 Users
0 Likes
746 Views
 Hans
(@hans)
Famed Member Admin
Joined: 9 years ago
Posts: 2311
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:

#!/bin/bash

# dirnumber generates the name of the output directory
dirnumber=1

# base directory
basedir=/path/to/base/dir

# the number of files we have moved
filesmoved=0

# number of files per dir
filesindir=50

# 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
      outdir=$basedir/$dirnumber
      mkdir $outdir
      ((dirnumber++))
   fi
   
   # 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
   ((filesmoved++))

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

   
ReplyQuote

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).

Share: