Golang : 如何删除文件中的某些行

688 阅读1分钟

这里有一个简单的教程,介绍如何从一个文件中删除某些行的数据。有些时候,由于一些不可预见的原因,一些被下载的文件包含了更多需要的数据,例如在文件开头的额外HTTP请求头信息。

那么,如何去删除这些不需要的信息呢?

解决这个问题的方法类似于将一个文件复制到一个新的文件,只是在复制过程中,不需要的数据被省略掉了。在下面的代码例子中,我们将删除文件开头的不需要的数据,只是忽略这些行。一旦检测到一个标记%startHERE ,那么我们才开始读取其余的数据。

在这里,你可以了!

注意:为了简单起见,我们将使用corruptFile常量来模拟一个文件。对于你自己的生产使用,取消注释这些行,从一个实际的文件读取。


 package main

 import (
  "fmt"
  //"io/ioutil"
  //"os"
  "strings"
 )

 const corruptFile = `HTTP 2.0 OK
 Content-Length :123456

 %startHERE
 some real data bytes
 more bytes`

 func main() {

  // UNCOMMENT these lines to read in from an actual file instead.
  //if len(os.Args) <= 1 {
  // fmt.Printf("USAGE : %s  \n", os.Args[0])
  // os.Exit(0)
  //}

  //fileName := os.Args[1]

  //fileBytes, err := ioutil.ReadFile(fileName)

  //if err != nil {
  // fmt.Println(err)
  // os.Exit(1)
  //}

  //lines := strings.Split(string(fileBytes), "\n")

  lines := strings.Split(string(corruptFile), "\n")

  startPrint := false

  for i, line := range lines {
 // only print after %startHERE
 if equal := strings.Index(line, "%startHERE"); equal > 0 {
 startPrint = true
 }

 if startPrint {
 fmt.Println(i, line)
 // instead of printing to the screen, this is where
 // you want to start writing to a new file a.k.a copying the file

 // how it is done at https://www.socketloop.com/tutorials/golang-simple-file-scaning-and-remove-virus-example
 }
  }

 }

希望这对你有帮助,祝你编码愉快