Version 6 of grep

Updated 2005-06-08 19:13:42

grep is the name of a common utility on many Unix or unix like systems.

Folklore says that the name represents a command that developers in the old days used to issue within their editor or other similar program:

   g/re/p

which was a global {regular expression} print command.

Grep reads through one or more input streams (stdin or files), searching for a string of text which represents some for of a regular expression, and, depending on options provided, may produce the matching lines of input.


RS wrote this tiny, and feature-poor, emulation for use on PocketPC (but it should run elsewhere too):


 proc grep {re args} {
    set files [eval glob -types f $args]
    foreach file $files {
       set fp [open $file]
       while {[gets $fp line] >= 0} {
          if [regexp -- $re $line] {
             if {[llength $files] > 1} {puts -nonewline $file:}
             puts $line
           }
       }
       close $fp
    }
 }

# Test:

  catch {console show}
  puts "Result:\n[grep "require" "*.tcl"]"

Here's another version - I wrote this out of desperation because the real grep -f ate up all my memory, and then busted, under Cygwin (remove the leading blank in the # line for an executable script):


 #!/usr/bin/env tclsh
 proc main argv {
    set usage {usage: grep-f.tcl refile ?file...? > outdata}
    if {[llength $argv]<1} {puts $usage; exit}

    set fp [open [lindex $argv 0]]
    set REset [split [string trim [read $fp]] \n]
    close $fp

    if {[llength $argv] == 1} {
        grep-f $REset stdin
    } else {
        foreach file [lrange $argv 1 end] {
            set fp [open $file]
            grep-f $REset $fp
            close $fp
        }
    }
 }
 proc grep-f {REset fp} {
    while {[gets $fp line] >= 0} {
        foreach RE $REset {
            if {[regexp $RE $line]} {
                puts $line
                break
            }
        }
    }
 }
 main $argv

See also: a grep-like utility - A little file searcher with GUI - Example Scripts Everybody Should Have


category application