**What is sorting?** Sorting is taking a collection of things and putting them into some specific order. For example, sorting people by age, shoes by size, strings by length, planets by mass, numbers by value. **What techniques are available within the Tcl language?** * '''[lsort]''' — takes a Tcl [list] argument and returns another list that is the sorted version of the input list. The other arguments determine exactly how the items in the list are to be ordered. **What are other relevant pages on the wiki?** * [merge sorts] * [collation] * [custom sorting] * [How fast can we sort 5 elements] * [Sorted Lists] * [Topological sort] * [Simple Text Widget Sort] ---- Frequently Asked Questions about sorting * How can I sort the contents of a file in tcl? For sorting the lines of a file being read from standard input, and writing the result out to standard output, one can use the following one-liner: puts [join [lsort [split [read -nonewline stdin] \n]] \n] Or in English: read in all the data to sort, split it into the list of units to be sorted, sort that list, join the sorted list back up in the external format, and write it out. [AMG]: At least on [Unix], most files end with a newline. The above code interprets newlines as line separators, not line terminators, so when the last character of the file is a newline, it thinks a zero-length line follows. `[[[regsub] {\n$} [[[read] [stdin]]] ""]]` can be used to get the contents of the file sans a trailing newline. '''[AK] - 2010-03-05 13:15:20''': IMHO `[[string trimright [[read stdin]] \n]]` looks nicer and easier to understand. Internally simpler too I would guess (No regexp engine). On the other hand, this code chops all trailing newlines, i.e. from the higher perspective, all trailing empty lines. Not just one. [AMG]: I guess it depends on the application. A general-purpose sort utility should probably kill only the final newline, but more specialized programs would likely want to eliminate all leading and trailing blank lines (`[[[string trim] [[read stdin]] \n]]`), or even all internal blank lines (`[[regsub -all {\n{2,}} ... \n]]`), depending on the input syntax. Also they could get rid of comment lines, etc. As for myself, I think I'll go with [[string trim]] as a reasonable approximation, unless I am writing a program that must preserve leading and trailing blank lines. [Lars H], 2010-03-06: Even easier: add the -nonewline switch to [read]. Made that change in the code above. <>Discussion