0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

バックスラッシュエスケープされたタブ区切りテキストをCSVに変換する

Posted at

以下サンプル

tsv2csv.go
//usr/bin/go run $0 $@ ; exit
package main

import (
        "bufio"
        "encoding/csv"
        "fmt"
        "os"
        "strings"
)

func main() {
        // 標準入力からデータを読み込む
        scanner := bufio.NewScanner(os.Stdin)

        // CSVライターを作成し、標準出力に書き込む
        writer := csv.NewWriter(os.Stdout)
        defer writer.Flush()

        // 標準入力を1行ずつ読み込み
        for scanner.Scan() {
                // タブ区切りでフィールドを分割
                line := scanner.Text()
                fields := strings.Split(line, "\t")

                // 各フィールドのエスケープシーケンスを処理
                for i, field := range fields {
                        fields[i] = unescape(field)
                }

                // CSVとして書き込む
                if err := writer.Write(fields); err != nil {
                        fmt.Println("Error writing record to csv:", err)
                        return
                }
        }

        if err := scanner.Err(); err != nil {
                fmt.Println("Error reading input:", err)
        }
}

// エスケープシーケンスを処理する関数
func unescape(s string) string {
        if !strings.Contains(s, "\\"){
                return s
        }

        var builder strings.Builder
        length := len(s)

        for i := 0; i < length; i++ {
                if s[i] == '\\' && i+1 < length {
                        switch s[i+1] {
                        case 'n':
                                builder.WriteByte('\n')
                                i++
                        case 't':
                                builder.WriteByte('\t')
                                i++
                        case '\\':
                                builder.WriteByte('\\')
                                i++
                        default:
                                builder.WriteByte(s[i])
                        }
                } else {
                        builder.WriteByte(s[i])
                }
        }
        return builder.String()
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?