I mainly need to read a specific range of lines in a file, and if a string is matched to an index string (let's say "Hello World!" for example) return true, but I'm not sure how to do so. I know how read individual lines and whole files, but not ranges of lines. Are there any libraries out there that can assist, or there a simple script to do it w/? Any help is greatly appreciated!
Something like this?
package main
import (
"bufio"
"bytes"
"fmt"
"os"
)
func Find(fname string, from, to int, needle []byte) (bool, error) {
f, err := os.Open(fname)
if err != nil {
return false, err
}
defer f.Close()
n := 0
scanner := bufio.NewScanner(f)
for scanner.Scan() {
n++
if n < from {
continue
}
if n > to {
break
}
if bytes.Index(scanner.Bytes(), needle) >= 0 {
return true, nil
}
}
return false, scanner.Err()
}
func main() {
found, err := Find("test.file", 18, 27, []byte("Hello World"))
fmt.Println(found, err)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With