Go: Reading a specific range of lines in a file

huangapple go评论77阅读模式
英文:

Go: Reading a specific range of lines in a file

问题

我主要需要读取文件中的特定行范围,如果一个字符串与索引字符串匹配(比如说"Hello World!"),则返回true,但我不确定如何实现。我知道如何读取单独的行和整个文件,但不知道如何读取行范围。是否有任何可以帮助的库,或者有没有简单的脚本可以实现?非常感谢您的帮助!

英文:

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!

答案1

得分: 8

像这样吗?

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)
}
英文:

Something like this?

package main

import (
	&quot;bufio&quot;
	&quot;bytes&quot;
	&quot;fmt&quot;
	&quot;os&quot;
)

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 &lt; from {
			continue
		}
		if n &gt; to {
			break
		}
		if bytes.Index(scanner.Bytes(), needle) &gt;= 0 {
			return true, nil
		}
	}
	return false, scanner.Err()
}

func main() {
	found, err := Find(&quot;test.file&quot;, 18, 27, []byte(&quot;Hello World&quot;))
	fmt.Println(found, err)
}

答案2

得分: -1

如果你正在使用for循环来遍历一段行的切片,你可以使用以下类似的代码:

for _, line := range file[2:40] {
    // 做一些操作
}
英文:

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
}

huangapple
  • 本文由 发表于 2014年9月2日 08:09:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/25614176.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定