split files into folders in linux

How to Split Folder into Subfolders in Linux

Sometimes you may have a large number of files in one folder and want to split folder into subfolders in Linux. You can easily do this using shell script in Linux. In this article, we will learn how to split folder into subfolders in Linux.


How to Split Folder into Subfolders in Linux

Here are the steps to split folder into subfolders in Linux. Let us say you have a folder /home/ubuntu/data with 1000 files. We will split it into multiple folders named dir_001, dir_002, etc. each containing 100 files.

Open terminal and go to the folder.

cd /home/ubuntu/data

Run the following code in terminal.

i=0; 
for f in *; 
do 
    d=dir_$(printf %03d $((i/100+1))); 
    mkdir -p $d; 
    mv "$f" $d; 
    let i++; 
done

In the above code, we iterate through each file in the folder one by one. We also maintain a file counter i. Using this file counter, we determine its folder index 001, 002, etc. and use it to create its directory name dir_001, dir_002, etc. For each file, we run mkdir -p command that creates a folder dir_001, dir_002, etc. for every hundred files and moves each file into its directory. Each folder is created only if it doesn’t exist. In this case, files 1-100 will to into dir_001, files 101-200 will go to dir_002, etc.

You can customize the above code as per your requirements. In this short article, we have learnt how to split folder of files into subfolders in Linux.

Also read:

How to Sort Files into Folders in Linux
How to Add Newline After Pattern in Vim
How to Convert CRLF to LF in Linux
How to Store Command in Variable in Shell Script
Tar Directory Exclude Files & Folders

Leave a Reply

Your email address will not be published. Required fields are marked *