将mysql的dump的sql文件转为csv

两个假设:

  • 每个表一个单独sql
  • 不导出行头

代码:

package main

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

func main() {

  if len(os.Args) != 3 {
    fmt.Println("Usage:\n mysql2csv <input> <output>")
    return
  }

  b, err := ioutil.ReadFile(os.Args[1])
  if err != nil {
    panic(err)
  }
  str := string(b)
  reg := regexp.MustCompile(`(?m)^INSERT INTO.*?$`)
  res := reg.FindAllStringSubmatch(str, -1)

  f, err := os.OpenFile(os.Args[2], os.O_WRONLY|os.O_CREATE, 0600)
  if err != nil {
    panic(err)
  }
  defer f.Close()

  for _, sub := range res {
    s := strings.Index(sub[0], "(")
    e := strings.LastIndex(sub[0], ")")
    tuples := strings.Split(sub[0][s+1:e], "),(")
    for _, tuple := range tuples {
      io.WriteString(f, tuple)
      io.WriteString(f, "\n")
    }
  }
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *