diff src/ut/lu/lu.go @ 18:45ca03520eea

ut: add grep.
author pyon@macmini
date Sat, 23 Jun 2018 09:38:15 +0900
parents 72ce457fb99d
children 8008046c8d76
line wrap: on
line diff
--- a/src/ut/lu/lu.go	Wed Jun 20 06:01:58 2018 +0900
+++ b/src/ut/lu/lu.go	Sat Jun 23 09:38:15 2018 +0900
@@ -16,6 +16,7 @@
     "os"
     "os/exec"
     "path/filepath"
+    "regexp"
     "strings"
 )
 
@@ -208,11 +209,76 @@
     }
 }
 
+/* grep: done. */
 func Grep( word string, inv bool, files []string ) {
+    regex, err := regexp.Compile( word )
+    if err != nil {
+        log.Fatal( err )
+    }
     if len( files ) == 0 {
-        fmt.Println("grep stdin")
+        grep( regex, inv, os.Stdin )
     } else {
-        fmt.Println("grep")
+        for _, file := range files {
+            f, _ := os.Open( file )
+            grep( regex, inv, f )
+            f.Close()
+        }
+    }
+}
+
+func grep( regex *regexp.Regexp, inv bool, r io.Reader ) {
+    input := bufio.NewScanner( r )
+    for input.Scan() {
+        if regex.MatchString( input.Text() ) && !inv {
+            fmt.Println( input.Text() )
+        }
+        if !regex.MatchString( input.Text() ) && inv {
+            fmt.Println( input.Text() )
+        }
+    }
+}
+
+/* orgrep: done. */
+func OrGrep( lfile string, inv bool, files []string ) {
+    var keywords []regexp.Regexp
+    f, _ := os.Open( lfile )
+    input := bufio.NewScanner( f )
+    for input.Scan() {
+        regex, err := regexp.Compile( input.Text() )
+        if err != nil {
+            log.Fatal( err )
+        }
+        keywords = append( keywords, *regex )
+    }
+    f.Close()
+
+    if len( files ) == 0 {
+        orgrep( keywords, inv, os.Stdin )
+    } else {
+        for _, file := range files {
+            f, _ := os.Open( file )
+            orgrep( keywords, inv, f )
+            f.Close()
+        }
+    }
+}
+
+func orgrep( keywords []regexp.Regexp, inv bool, r io.Reader ) {
+    input := bufio.NewScanner( r )
+    seen := make( map[string]bool )
+    for input.Scan() {
+        for _, r := range keywords {
+            if r.MatchString( input.Text() ) {
+                seen[ input.Text() ] = true
+            }
+        }
+        if !inv && seen[ input.Text() ] {
+            fmt.Println( input.Text() )
+        }
+        if inv && !seen[ input.Text() ] {
+            fmt.Println( input.Text() )
+        }
+        seen[ input.Text() ] = false
     }
 }