Skip to content

Commit e71af8a

Browse files
committed
Added a simple tab 2 csv converter
1 parent 463e2d8 commit e71af8a

File tree

2 files changed

+107
-1
lines changed

2 files changed

+107
-1
lines changed

CITATION.cff

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,4 +7,4 @@ authors:
77
orcid: https://orcid.org/0000-0003-0900-6903
88
version: 1.0.5-dev
99
title: datatools
10-
date-released: 2022-01-19
10+
date-released: 2022-01-27

cmd/tab2csv/tab2csv.go

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
//
2+
// tabs2csv converts a tab delimited file to a CSV formatted file.
3+
//
4+
// @author R. S. Doiel, <[email protected]>
5+
//
6+
package main
7+
8+
import (
9+
"encoding/csv"
10+
"flag"
11+
"fmt"
12+
"os"
13+
"path"
14+
15+
// Caltech Library Packages
16+
"github.com/caltechlibrary/datatools"
17+
)
18+
19+
var (
20+
description = `
21+
USAGE
22+
23+
%s is a simple conversion utility to convert from tabs to quoted CSV.
24+
%s reads from standard input and writes to standard out.
25+
26+
`
27+
28+
examples = `
29+
If my.tab contained
30+
31+
name email age
32+
Doe, Jane [email protected] 42
33+
34+
Concert this to a CSV file format
35+
36+
%s < my.tab
37+
38+
This would yield
39+
40+
"name","email","age"
41+
"Doe, Jane","[email protected]",42
42+
43+
`
44+
45+
// Standard Options
46+
showHelp bool
47+
showLicense bool
48+
showVersion bool
49+
)
50+
51+
func main() {
52+
appName := path.Base(os.Args[0])
53+
54+
flag.BoolVar(&showHelp, "h", false, "display help")
55+
flag.BoolVar(&showHelp, "help", false, "display help")
56+
flag.BoolVar(&showLicense, "license", false, "display license")
57+
flag.BoolVar(&showVersion, "version", false, "display version")
58+
59+
// Parse Environment and Options
60+
flag.Parse()
61+
62+
if showHelp {
63+
fmt.Fprintf(os.Stdout, description, appName, appName)
64+
fmt.Fprintf(os.Stdout, examples, appName)
65+
os.Exit(0)
66+
}
67+
if showLicense {
68+
fmt.Fprintln(os.Stdout, datatools.LicenseText, appName, datatools.Version)
69+
os.Exit(0)
70+
}
71+
if showVersion {
72+
fmt.Fprintln(os.Stdout, datatools.Version)
73+
os.Exit(0)
74+
}
75+
76+
exitCode := 0
77+
// Setup the CSV output
78+
r := csv.NewReader(os.Stdin)
79+
r.Comma = '\t'
80+
r.Comment = '#'
81+
w := csv.NewWriter(os.Stdout)
82+
/*
83+
if delimiter != "" {
84+
w.Comma = datatools.NormalizeDelimiterRune(delimiter)
85+
}
86+
*/
87+
for {
88+
row, err := r.Read()
89+
if err != nil {
90+
fmt.Fprintln(os.Stderr, err)
91+
exitCode = 1
92+
break
93+
} else {
94+
if err := w.Write(row); err != nil {
95+
fmt.Fprintln(os.Stderr, err)
96+
exitCode = 1
97+
}
98+
w.Flush()
99+
if err := w.Error(); err != nil {
100+
fmt.Fprintln(os.Stderr, err)
101+
exitCode = 1
102+
}
103+
}
104+
}
105+
os.Exit(exitCode)
106+
}

0 commit comments

Comments
 (0)