Golang:在文件中查找字符串并显示行号

Ale*_*. b 7 string algorithm loops go

read, err := ioutil.ReadFile(path)
if err != nil {
    return err
}

if strings.Contains(string(read), "STRING") {
    // display line number?
    // what if many occurrences of the string
    // how to display for each the line number?
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试搜索特定字符串的文件并显示字符串所在的行号.

eli*_*rar 18

使用扫描程序逐行遍历文件,增加每个循环的行数.

例如

f, err := os.Open(path)
if err != nil {
    return 0, err
}
defer f.Close()

// Splits on newlines by default.
scanner := bufio.NewScanner(f)

line := 1
// https://golang.org/pkg/bufio/#Scanner.Scan
for scanner.Scan() {
    if strings.Contains(scanner.Text(), "yourstring") {
        return line, nil
    }

    line++
}

if err := scanner.Err(); err != nil {
    // Handle the error
}
Run Code Online (Sandbox Code Playgroud)

更新:如果您需要在"数千个文件"中执行此操作(根据另一个答案的注释),那么您可以将此方法包装在工作池中并同时运行.

  • 最好使用“scanner.Bytes()”和“bytes.Contains”来避免从“[]byte”到“string”的转换。我不确定工作池是否会在数千个文件的情况下有所帮助——代码将是(或应该是)io 绑定的,并且多个 goroutine 将意味着更多的磁盘查找。 (2认同)