Gnocl Cookbook‎ > ‎

Sorting Text Into Lists

Working with text files often require working with lists of words. Here's a simple script solution the problem of sorting out those messy lists and removing any duplicates.

# text-sort.tcl
# Sort list of words contained within a text widget.
# Description:
# -----------
# Copy the words to a tcl list, sort them and the
# re-insert into original text.

# the next line restarts using tclsh \
exec tclsh "$0" "$@"

package require Gnocl

 proc sorttxt {w {first start} {last end} args} {
    if {[$w class] != "text"} {return 0}
    set str [$w get $first $last]
    regsub -all -line -- {^\s+|\s+$} $str {} str
    $w erase $first $last
    $w insert $first [join [eval lsort $args [list [split $str \n]]] \n]
    return 1

set txt1 [gnocl::text -text "Zebra\nWildebeast\nParrot\nHamster\nBear\nAardvark\nParrot"]

gnocl::window -child $txt1 -widthRequest 200 -heightRequest 200

puts [sorttxt $txt1  start end -dictionary -unique]

PS> The GLibs integral to the Gnocl environment provide excellent resources for the creation and management of lists. With this in mind, its quite feasible to move this functionality into the Gnocl core code itself.