Script to move files under their first letter name

i've a lot of files (1000+) in a single directory, and i would like to organize them into sub directories, according to their first letter. So i've 200 files starting with A, and i would like to move them into subdirectory "A", then all "B" files etc. etc.

How to do ?


Solution 1:

In a terminal: cd into the directory in question, then

for x in `ls -1 | sed -e 's/^\(.\).*/\1/' | sort -u`; do
mkdir $x && mv -i ${x}?* $x
done

This assumes that no files have a single character name before you start. If they do, you might move them aside before you run the above procedure:

mkdir singles && mv ? singles

and then move them to their appropriate destinations aftwards.

Edit: See the comments below for some caveats. If you run into problems with too long command lines, you could replace the second line by

mkdir $x && find . -maxdepth 1 -name "${x}?*" -exec mv -i {} $x \;

Solution 2:

Here's a Ruby one-liner:

ruby -e 'require "FileUtils"; Dir["*"].each { |f| next if File.directory?(f); d = f[0]; Dir.mkdir d rescue nil; FileUtils.mv(f,d) }'

It basically iterates over all files, creates the directories if possible and moves the files to it afterwards.

Just execute this line from the directory.