Go: Reading a specific range of lines in a file

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

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

像这样吗?

  1. package main
  2. import (
  3. "bufio"
  4. "bytes"
  5. "fmt"
  6. "os"
  7. )
  8. func Find(fname string, from, to int, needle []byte) (bool, error) {
  9. f, err := os.Open(fname)
  10. if err != nil {
  11. return false, err
  12. }
  13. defer f.Close()
  14. n := 0
  15. scanner := bufio.NewScanner(f)
  16. for scanner.Scan() {
  17. n++
  18. if n < from {
  19. continue
  20. }
  21. if n > to {
  22. break
  23. }
  24. if bytes.Index(scanner.Bytes(), needle) >= 0 {
  25. return true, nil
  26. }
  27. }
  28. return false, scanner.Err()
  29. }
  30. func main() {
  31. found, err := Find("test.file", 18, 27, []byte("Hello World"))
  32. fmt.Println(found, err)
  33. }
英文:

Something like this?

  1. package main
  2. import (
  3. &quot;bufio&quot;
  4. &quot;bytes&quot;
  5. &quot;fmt&quot;
  6. &quot;os&quot;
  7. )
  8. func Find(fname string, from, to int, needle []byte) (bool, error) {
  9. f, err := os.Open(fname)
  10. if err != nil {
  11. return false, err
  12. }
  13. defer f.Close()
  14. n := 0
  15. scanner := bufio.NewScanner(f)
  16. for scanner.Scan() {
  17. n++
  18. if n &lt; from {
  19. continue
  20. }
  21. if n &gt; to {
  22. break
  23. }
  24. if bytes.Index(scanner.Bytes(), needle) &gt;= 0 {
  25. return true, nil
  26. }
  27. }
  28. return false, scanner.Err()
  29. }
  30. func main() {
  31. found, err := Find(&quot;test.file&quot;, 18, 27, []byte(&quot;Hello World&quot;))
  32. fmt.Println(found, err)
  33. }

答案2

得分: -1

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

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

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

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

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:

确定