A little file searcher

Summary

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.

WikiDbImage tgrep.jpg

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).

Code


 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
 }
  set f [lindex $argv 0]
  if {$f eq ""} { set f [tk_getOpenFile] } ;# MG
  if {![file exists $f]} exit ;# MG
  readfile $f data
  ui

Comments

HJG Calling this script without a filename as argument puts up an error-message. Same if the file does not exist. It would be nice to catch this...
RS: Depends. I used the tool from the command line, with tab-completed filename. Tcl's error message

 couldn't open "foofoo": no such file or directory

is sufficiently clear to me :^) Scripts that I write at work for other people to use, have a usage message that is shown when called with no arguments, but adding that would have made this file searcher less "little". For Wiki pages, I prefer to post minimal code, so the "bare bones" of what goes on are easily visible. Anyone is free to add what features he wants, but please do it in a comment at bottom of page, not by changing the original script.

MG adds (on June 8 2005) a change that makes it call tk_getOpenFile, if you don't specify a file on the command line, and then exit (silently) if the file given (via command-line or tk_getOpenFile) doesn't exist.


See also: incrFilter and A grep-like utility - A little file searcher (iPaq) - Another little file search