Sorting Files according to their Extensions...

I am trying to write a Korne Shell Script wherein we have to sort
files according to their extensions(for eg. 1.sh, 5.sh, 9.sh together;
4.csh, 120.csh, 6.csh together and 7.ksh, 2.ksh, 59.ksh together) and
move them to their respective directories viz. sh, csh and ksh...

I think, Regular Expressions can be used here for sorting.

Any Inputs please...

Thanks a lot in advance..

First make a list of all entensions in use. Then move each set of files with that extension.

EXT_LIST=$(ls | awk -F. 'NF>1{print $NF}' | sort -u)
for i in $EXT_LIST; do
  mkdir -p $i
  mv *.$i $i || rmdir $i 2>/dev/null
done
  • If you don't include "NF>1" then files without extensions will be included (not good).
  • the "-u" flag of "sort" limits the list to unique values
  • the "rmdir" on failure of "mv" is to remove bad.dirs.created.from.weirdly.named.files!!!