-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrecsv.go
More file actions
65 lines (59 loc) · 1.17 KB
/
recsv.go
File metadata and controls
65 lines (59 loc) · 1.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package main
import (
"cmp"
"encoding/csv"
"log"
"os"
"slices"
)
func main() {
inFile := os.Stdin
outFile := os.Stdout
argc := len(os.Args)
var err error
if argc > 1 {
inFile, err = os.Open(os.Args[1])
if err != nil {
log.Fatal(err)
}
defer inFile.Close()
}
if argc > 2 {
outFile, err = os.Create(os.Args[2])
if err != nil {
log.Fatal(err)
}
defer outFile.Close()
}
reader := csv.NewReader(inFile)
// ReadAll reads all the records from the CSV file
// and Returns them as slice of slices of string
// and an error if any
records, err := reader.ReadAll()
// Checks for the error
if err != nil {
log.Println("Error reading records")
}
// Sort input CSV lines
slices.SortFunc(records, func(a, b []string) int {
eq := 0
for i := 0; i < len(a) && eq == 0; i++ {
eq = cmp.Compare(a[i], b[i])
}
return eq
})
w := csv.NewWriter(outFile)
// Loop to iterate through
// and write out each of the string slice
for _, eachrecord := range records {
err = w.Write(eachrecord)
if err != nil {
log.Println("Error writing records")
}
}
w.Flush()
err = w.Error()
if err != nil {
log.Fatalln(err, "Writing report output to CSV")
}
}