Go语言搜索某个大文件中是否包含特定字符串

package main

import (
    "time"
    "os"
    "bufio"
    "strconv"
    "log"
    "bytes"
)

var totalSize float64

func trace(msg string) func(){
    start := time.Now()
    log.Printf("%s", msg)
    return func() {
        elapse := time.Since(start)
        log.Printf("exit %s (%s) %.2fMB/s", msg, elapse, totalSize / elapse.Seconds())
    }
}

func CheckFileContainsStr(path,str string) {
    cmp:=[]byte(str)
    log.Println(cmp)
    defer trace("file parser using golang")()
    f, err := os.Open(path)
    if err != nil {
        log.Printf("open file failed, %s", err)
    }
    defer f.Close()
    input := bufio.NewScanner(f)
    for input.Scan() {
        //log.Println(input.Bytes())
        info:=input.Bytes()        
        if bytes.Contains(info,cmp){
            log.Println(info)
        }
        
        tokens := bytes.SplitN(input.Bytes(), []byte(" "), 10)
        //log.Println(tokens)
        totalSize += float64(len(input.Bytes()))
        if len(tokens) < 9 {
            continue
        }
        strconv.ParseInt(string(tokens[8]), 10, 0)
    }
    totalSize = totalSize / (1 << 20)
}

func main(){
   CheckFileContainsStr("~/Downloads/manager.jsp","JspSpyPwd")
}
Go语言搜索某个大文件中是否包含特定字符串_第1张图片

你可能感兴趣的:(GO)