sort files into folders

How to Sort Files Into Folders in Linux

Linux provides numerous tools and commands to work with files & folders. Sometimes you may need to sort files into folders by date, sort files by name, by filetype. In this article, we will learn how to sort files into folders in Linux.


How to Sort Files Into Folders in Linux

We will look at several use cases to sort files into folders in Linux. We will use simple shell scripting for our purpose.

Let us say you have a bunch of files in /home/ubuntu/data folder. Here is the simple shell script to sort files by name in Linux.

cd /home/ubuntu/data
for f in *; do
  if [ -f "$f" ]; then
    mkdir -p "$f"
    mv "$f" "$f"
  fi
done
cd -

In the above code, we basically go to folder /home/ubuntu/data. Once we are inside the folder, we use a for loop to go through the files one by one. For each file, we issue a mkdir -p command to create a separate folder based on the filename, if it doesn’t exist already.

Next, we issue a mv command to move the current file to that folder. Once we do this for all files, we cd back to our previous folder.

If you don’t want to create separate folder for each filename but only the first letter of their filename, you can modify the above code, as shown below. In this case, we extract the first letter of filename to create folder and move file into it.

cd <yourdir>
for f in *; do
  if [ -f "$f" ]; then
    mkdir -p "${f:0:1}"
    mv "$f" "${f:0:1}"
  fi
done
cd -

In this article, we have learnt how to sort files into folders by their name. You can customize this code as per your requirement.

Also read:

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 Excluding Files & Folders
How to Change Color Scheme in Vim

Leave a Reply

Your email address will not be published.