perl -plwe'$h{$_}++ } for (sort { length($a)<=>length($b) } keys %h) {' infile >infile.tmp #### perl -i.bak -plwe'$h{$_}++; last if eof } for (sort { length($a)<=>length($b) } keys %h) {' infile