Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: Reading a specific range of lines in a file

Tags:

file

range

go

line

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!

like image 677
T145 Avatar asked Feb 12 '23 03:02

T145


1 Answers

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)
}
like image 89
peterSO Avatar answered Feb 16 '23 03:02

peterSO