5

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!

2 Answers 2

8

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)
}
Sign up to request clarification or add additional context in comments.

1 Comment

Precisely! Thank you very much!
-1

If you're using for to iterate through a slice of lines, you could use something along the lines of

for _,line := range file[2:40] {
    // do stuff
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.