Parse Pipe-Delimited Records With encoding/csv

Configure csv.Reader with a pipe Comma, hash Comment, and TrimLeadingSpace, then normalize whitespace and re-export the rows as TSV.

GoData Integrity

Code

snippet
package main

import (
	"bytes"
	"encoding/csv"
	"fmt"
	"strings"
)

func main() {
	input := strings.Join([]string{
		"# service routing table",
		"service | port | mode",
		"  auth  | 8081 | strict",
		"billing | 8082 | shadow",
	}, "\n")

	reader := csv.NewReader(strings.NewReader(input))
	reader.Comma = '|'
	reader.Comment = '#'
	reader.TrimLeadingSpace = true

	records, err := reader.ReadAll()
	if err != nil {
		fmt.Println("csv read failed:", err)
		return
	}
	fmt.Printf("parsed %d rows:\n", len(records))

	var out bytes.Buffer
	writer := csv.NewWriter(&out)
	writer.Comma = '\t'
	for _, row := range records {
		for i := range row {
			row[i] = strings.TrimSpace(row[i])
		}
		if err := writer.Write(row); err != nil {
			fmt.Println("csv write failed:", err)
			return
		}
	}
	writer.Flush()
	if err := writer.Error(); err != nil {
		fmt.Println("flush error:", err)
		return
	}
	fmt.Print(out.String())
}

Execution breakdown — Parse Pipe-Delimited Records With encoding/csv

Core implementation sits cleanly inside the helper main.

The loop for _, row := range records is the only repeated construct. Nothing falls through silently — 3 checkpoints test err != nil on the way through.

Caveats

  • Install steps are unnecessary because stdlib covers the whole sample.

Applying it

The entry-point signature is func main()

The run emits 4 labeled sections — csv read failed:, parsed, csv write failed:, flush error: — one per step.

Statements that matter

for _, row := range records {
	for i := range row {
		row[i] = strings.TrimSpace(row[i])
	}
	if err := writer.Write(row); err != nil {
		fmt.Println("csv write failed:", err)
		return
	}
}
if err != nil {
	fmt.Println("csv read failed:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does Parse Pipe-Delimited Records With encoding/csv print when run?
No setup needed: run the file and look for labeled lines like `csv read failed:`, `parsed`, `csv write failed:` in the output.