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!
[Solved] Linux/macOS - How to split a directory into multiple directories
(@hans)
Famed Member Admin
Joined: 11 years ago
Posts: 2762
Topic starter
April 7, 2022 4:50 AM
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