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.
Code
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
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.ASCII85 EncoderEncode and decode ASCII85 (Base85), the Adobe variant with z zero-compression, handling arbitrary bytes and Unicode.Base32 Encoder & DecoderEncode and decode RFC 4648 Base32 with padding, fully UTF-8 safe so Unicode text round-trips without corruption. Nothing leaves your browser.Base45 Encoder and DecoderEncode and decode text with the Base45 alphabet defined in RFC 9285, with UTF-8 support, padding-free output, and clear validation errors.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.