Version 8 of A little file searcher

Updated 2003-02-18 12:25:10

http://mini.net/files/tgrep.jpg Richard Suchenwirth 2002-07-21 - I needed such a little tool at work, and thought that other Tclers could use it too. Basically it is a small UI wrapper for searching a text file (like a no-frills grep). Specify your search term in the entry above, hit <Return>, and see in the text which lines from the file given at startup matched. For convenience, case is ignored (one might make this switchable); the entry is cleared on cursor <Up>; and the number of matching lines is displayed in the end.

Currently I don't need it, but with a few lines more, encoding configuration (e.g. for Chinese or Korean) could be built in... Only, typing the search term would require a little input manager (as in taiku goes multilingual).


 proc ui {} {
    entry     .e -bg white -textvar search
    bind .e <Return> {search $search .t}
    bind .e <Up>     {set search ""}
    text      .t -yscrollcommand ".y set" -bg white -wrap word
    scrollbar .y -command ".t yview"

    grid .e - -sticky ew
    grid .t .y -sticky news
    grid columnconfig . 0 -weight 1
    grid rowconfig . 1 -weight 1
 }
 proc readfile {file varName} {
    upvar \#0 $varName data
    set fp [open $file]
    set data [split [read $fp] \n]
    close $fp
    wm title . $file
 }
 proc search {re w} {
    global data
    $w delete 1.0 end
    set n 0
    foreach line $data {
        if {[regexp -nocase -- $re $line]} {
            $w insert end $line\n
            incr n
        }
    }
    $w insert end "Found $n lines"
    $w see end
 }
 readfile [lindex $argv 0] data
 ui 

http://mini.net/files/tgrep_ce.jpg The following version has been hand-tuned to look good, and work well, on the iPAQ:

 proc ui {} {
    entry     .e -bg white -textvar search
    bind .e <Return> {search $search .t}
    bind .e <Up>     {set search ""}
    button .x -text X -command exit -padx 0 -width 1 ;# explicit close button
    text      .t -width 43 -height 15 -yscrollcommand ".y set" -bg white -wrap word
    scrollbar .y -command ".t yview"

    grid .e .x -sticky ew
    grid .t .y -sticky news
    grid columnconfig . 0 -weight 1
    grid rowconfig . 1 -weight 1
 }
 proc search {re w} {
    global file
    $w delete 1.0 end
    set n 0
    set fp [open $file]
    while {[gets $fp line]>=0} {
        if {[regexp -nocase -- $re $line]} {
            $w insert end $line\n
            update idletasks
            incr n
        }
    }
    close $fp
    $w insert end "Found $n lines"
    $w see end
 }
 ui
 update idletasks ;# needed so the dialog is not killed
 focus .e
 wm geometry . +0+0
 set file [lindex $argv 0]
 if {$file == ""} {set file [tk_getOpenFile]}
 wm title . [file tail $file]

See also incrFilter and A grep-like utility


Arts and crafts of Tcl-Tk programming | Category Application