-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreplace_time.go
More file actions
97 lines (91 loc) · 2.1 KB
/
Copy pathreplace_time.go
File metadata and controls
97 lines (91 loc) · 2.1 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// -----------------------------------------------------------------------------
// CMDX Utilities Suite cmdx/[replace_time.go]
// (c) balarabe@protonmail.com License: GPLv3
// -----------------------------------------------------------------------------
package main
import (
"bytes"
"regexp"
"strings"
)
// replaceTime _ _
func replaceTime(cmd Command, args []string) {
if len(args) < 2 {
env.Println("'replace-time' requires: <source file> and <target file>")
return
}
var (
fromFile = args[0]
toFile = args[1]
)
var fromLines = map[string][]string{}
{
var lines []string
{
data, done := env.ReadFile(fromFile)
if !done {
return
}
content := strings.TrimSpace(string(data))
lines = strings.Split(content, "\n")
}
for _, line := range lines {
tm := rtExtractTime(line)
if tm == "" {
continue
}
fromLines[tm] = append(fromLines[tm], line)
}
}
var toLines []string
{
data, done := env.ReadFile(toFile)
if !done {
return
}
s := strings.TrimSpace(string(data))
toLines = strings.Split(s, "\n")
}
var out bytes.Buffer
{
var tmPrev string
for _, line := range toLines {
tm := rtExtractTime(line)
if tm != "" {
from, exist := fromLines[tm]
if exist {
if tm == tmPrev {
continue
}
tmPrev = tm
for _, s := range from {
out.WriteString(s + "\n")
}
continue
}
}
out.WriteString(line + "\n")
}
}
if !env.WriteFile(toFile, out.Bytes()) {
return
}
env.Printf("written '%s'\n", toFile)
}
var (
// `YYYY-MM-DD hh:mm ` and `YYYY-MM-DD hh:mm:ss ` (note the ending space)
rtValidTime1 = regexp.MustCompile(`^\d{4}-\d\d-\d\d \d\d:\d\d `)
rtValidTime2 = regexp.MustCompile(`^\d{4}-\d\d-\d\d \d\d:\d\d:\d\d `)
)
// rtExtractTime _ _
func rtExtractTime(line string) string {
var ret string
switch {
case rtValidTime2.MatchString(line):
ret = line[:19] + ":00" // 19 = length of 'YYYY-MM-DD hh:mm:ss'
case rtValidTime1.MatchString(line):
ret = line[:16] // 16 = length of 'YYYY-MM-DD hh:mm' in characters'
}
return ret
}
// end