Sorting file names by length of the file name

make test files:

mkdir -p test; cd test 
touch short-file-name  medium-file-name  loooong-file-name

the script:

ls |awk '{print length($0)"\t"$0}' |sort -n |cut --complement -f1

output:

short-file-name
medium-file-name
loooong-file-name

You can do like this

for i in `ls`; do LEN=`expr length $i`; echo $LEN $i; done | sort -n

for i in *; do printf "%d\t%s\n" "${#i}" "$i"; done | sort -n | cut -f2-

The simplest way is just:

$ ls | perl -e 'print sort { length($b) <=> length($a) } <>'

Tags:

Unix

Sorting