I always forget how to do this. Iterating over files with a bash for loop when the file name has a space.

  • There are few ways I tried using arrays and delimiters, but changing $IFS worked best.
  • In this case I’m sorting by the first lowercase letter or number.
files0="$(find -maxdepth 1 -type f -printf '%f;')"
save_ifs=$IFS
IFS=';'
for f in ${files0} ; do
    if [ -f $f ] ; then
        letter=$(echo $f | cut -c1 | tr A-Z a-z | tr 0-9 0)
        echo $letter - $f
        if [ ! -d $letter ] ; then
            mkdir $letter
        fi
        mv "$f" $letter/
    fi
done
IFS=$save_ifs