golang get the line number of the string in the file

Use scanner to iterate the file line by line, increasing the number of lines in each loop.

Examples are as follows:

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
}

If you need to do this in "thousands of files" (according to the comment of another answer), then you can wrap this method in a worker pool and run it at the same time.
 

 

Guess you like

Origin blog.csdn.net/whatday/article/details/114547217