comparison 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
comparison
equal deleted inserted replaced
17:72ce457fb99d 18:45ca03520eea
14 "io" 14 "io"
15 "log" 15 "log"
16 "os" 16 "os"
17 "os/exec" 17 "os/exec"
18 "path/filepath" 18 "path/filepath"
19 "regexp"
19 "strings" 20 "strings"
20 ) 21 )
21 22
22 func CmdTime( cmdline string ) { 23 func CmdTime( cmdline string ) {
23 cmd := exec.Command( "ls", "-l" ) 24 cmd := exec.Command( "ls", "-l" )
206 for i := len( buf ); i > 0; i-- { 207 for i := len( buf ); i > 0; i-- {
207 fmt.Println( buf[i-1] ) 208 fmt.Println( buf[i-1] )
208 } 209 }
209 } 210 }
210 211
212 /* grep: done. */
211 func Grep( word string, inv bool, files []string ) { 213 func Grep( word string, inv bool, files []string ) {
212 if len( files ) == 0 { 214 regex, err := regexp.Compile( word )
213 fmt.Println("grep stdin") 215 if err != nil {
214 } else { 216 log.Fatal( err )
215 fmt.Println("grep") 217 }
218 if len( files ) == 0 {
219 grep( regex, inv, os.Stdin )
220 } else {
221 for _, file := range files {
222 f, _ := os.Open( file )
223 grep( regex, inv, f )
224 f.Close()
225 }
226 }
227 }
228
229 func grep( regex *regexp.Regexp, inv bool, r io.Reader ) {
230 input := bufio.NewScanner( r )
231 for input.Scan() {
232 if regex.MatchString( input.Text() ) && !inv {
233 fmt.Println( input.Text() )
234 }
235 if !regex.MatchString( input.Text() ) && inv {
236 fmt.Println( input.Text() )
237 }
238 }
239 }
240
241 /* orgrep: done. */
242 func OrGrep( lfile string, inv bool, files []string ) {
243 var keywords []regexp.Regexp
244 f, _ := os.Open( lfile )
245 input := bufio.NewScanner( f )
246 for input.Scan() {
247 regex, err := regexp.Compile( input.Text() )
248 if err != nil {
249 log.Fatal( err )
250 }
251 keywords = append( keywords, *regex )
252 }
253 f.Close()
254
255 if len( files ) == 0 {
256 orgrep( keywords, inv, os.Stdin )
257 } else {
258 for _, file := range files {
259 f, _ := os.Open( file )
260 orgrep( keywords, inv, f )
261 f.Close()
262 }
263 }
264 }
265
266 func orgrep( keywords []regexp.Regexp, inv bool, r io.Reader ) {
267 input := bufio.NewScanner( r )
268 seen := make( map[string]bool )
269 for input.Scan() {
270 for _, r := range keywords {
271 if r.MatchString( input.Text() ) {
272 seen[ input.Text() ] = true
273 }
274 }
275 if !inv && seen[ input.Text() ] {
276 fmt.Println( input.Text() )
277 }
278 if inv && !seen[ input.Text() ] {
279 fmt.Println( input.Text() )
280 }
281 seen[ input.Text() ] = false
216 } 282 }
217 } 283 }
218 284
219 /* uniq: done. */ 285 /* uniq: done. */
220 func Uniq( cnt, dup bool, files []string ) { 286 func Uniq( cnt, dup bool, files []string ) {