Go:读取文件中特定范围的行

我主要需要读取文件中特定范围的行,如果字符串与索引字符串匹配(例如“Hello World!”),则返回 true,但我不知道该怎么做。我知道如何读取单个行和整个文件,但不知道如何读取行范围。是否有任何库可以提供帮助,或者有一个简单的脚本可以做到这一点?任何帮助是极大的赞赏!


万千封印
浏览 400回答 2
2回答

ibeautiful

像这样的东西?package mainimport (&nbsp; &nbsp; "bufio"&nbsp; &nbsp; "bytes"&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "os")func Find(fname string, from, to int, needle []byte) (bool, error) {&nbsp; &nbsp; f, err := os.Open(fname)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return false, err&nbsp; &nbsp; }&nbsp; &nbsp; defer f.Close()&nbsp; &nbsp; n := 0&nbsp; &nbsp; scanner := bufio.NewScanner(f)&nbsp; &nbsp; for scanner.Scan() {&nbsp; &nbsp; &nbsp; &nbsp; n++&nbsp; &nbsp; &nbsp; &nbsp; if n < from {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if n > to {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if bytes.Index(scanner.Bytes(), needle) >= 0 {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return true, nil&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return false, scanner.Err()}func main() {&nbsp; &nbsp; found, err := Find("test.file", 18, 27, []byte("Hello World"))&nbsp; &nbsp; fmt.Println(found, err)}

HUX布斯

如果您使用的for是遍历一段线,则可以使用类似以下内容的内容for _,line := range file[2:40] {&nbsp; &nbsp; // do stuff}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go