Skip to main content
1 of 3
Alex Jones
  • 6.5k
  • 18
  • 54
  • 85

sorts files according to their extensions

Suggestion need to overcome some limitations for this script:
I have made a script that will sort files according to their extension and place them in proper folder. for example, place abc.jpg in folder jpg

#!/bin/bash
#this script sorts files according to their extensions
oldIFS=$IFS
IFS=$'\n'
(find . -type f) > /tmp/temp
for var in `cat /tmp/temp`
do
name=`basename "$var"`
ext=`echo $name | cut -d'.' -f2- | cut -d'.' -f2- | cut -d'.' -f2- | cut -d'.' -f2- | cut -d'.' -f2- | cut -d'.' -f2- | cut -d'.' -f2-`
mkdir -p $ext
mv "$var" $ext/ 2> /dev/null
done
IFS=$oldIFS

problem with this script:

  1. it involves use of IFS, it is said to avoid use of IFS, as much as possible
  2. it does not sorts file without file extensions
  3. it will sort files like abc.tar.bz in folder named bz, but however such a file should go in tar.bz folder
  4. see line 9 of my script; if any file contain more no. of dots(in its name) than no. of cut -d'.' -f2- in the script than if will result in file name taken in extension part.
    for example, a file named i.am.live.in.india.and.i.study.computer.science.txt will be placed in folder named study.computer.science.txt

you may also suggest any tweaks to make this script more smaller and neat.

Alex Jones
  • 6.5k
  • 18
  • 54
  • 85