Monday, July 31, 2006

Sort based on string length

Sometimes you want to sort things based on the length of the string, especially in the situation where you want to do substitution. It works on my Cygwin.
sep="@"
awk -v sep=$sep '
  BEGIN {
    OFS=sep
  }
  {
    print length($0),$0
  }' textfile | sort -n -k 1 -r -t"$sep" | cut -f2 -d"$sep"

Labels: ,