Tag:golang go search
Package Mainimport ("Bufio" "bytes" "Flag" "FMT" "IO" "OS" "Path/filepath" "Sync/atomic") var re []bytevar Count Int32var C, f , d Boolvar I, p stringfunc main () {flag. Stringvar (&p, "P", "./", "-p=finddir")//Search the directory, the default is the current directory, Pathflag. Stringvar (&i, "R", "", "-r=matchstring")//keywords, indexflag. Boolvar (&c, "C", False, "-c=true")//whether the keyword is searched in the file content, Contentflag. Boolvar (&f, "F", False, "-f=true")//whether to find the file according to the keyword, fileflag. Boolvar (&d, "D", False, "-d=true")//whether to find folders based on keywords, directoryflag. Parse () If Len (i) = = 0 {fmt. PRINTLN ("keyword cannot be null") Return}re = []byte (i) if err: = FilePath. Walk (P, Walk); Err! = Nil {fmt. Println ("Walk:", err)}if count = = 0 {fmt. Println ("Search Path:", p) fmt. Println ("Keyword:", i) if D {fmt. Println ("Whether to search directory:", D)}if f {fmt. Println ("Whether to search for files:", f)}if C {fmt. Println ("Whether to search content:", c)}}fmt. Printf ("Total Found:%d\n", count)}func Walk (path string, info OS.) FileInfo, err Error) error {if Err! = Nil {return err}if info. Isdir () {if D && bytes. Contains ([]byte (info. Name ()), re) {atomic. AddInt32 (&count, 1) fmt. Println ("Match to Directory:", path)}return nil}if F {if bytes. Contains ([]byte (info. Name ()), re) {atomic. AddInt32 (&count, 1) fmt. Println ("Match to File:", path) return nil}}if C {return read (path)}return nil}//find the keyword in the file func read (path string) error {file, err: = OS. Open (path) defer file.close () if err! = Nil {fmt. Println (Path, ":", Err) return err}r: = Bufio. Newreader (File) I: = 0for {i++b, _, Err: = R.readline () if bytes. Contains (b, []byte{0}) {//Excludes binary files return nil}if err! = Nil {if Err = = Io. EOF {if bytes. Contains (b, re) {atomic. AddInt32 (&count, 1) fmt. Printf ("In file:%s line \ n", path, i) fmt. Println (String (bytes. Trimspace (b)))}return Nil}return err}if bytes. Contains (b, re) {atomic. AddInt32 (&count, 1) fmt. Printf ("In file:%s line \ n", path, i) fmt. Println (String (bytes. Trimspace (b))}}return nil}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Go 1.5 keyword Search directory, file, file content _ Fix a small bug