added lineParseAmount parameter

This commit is contained in:
Timon Ringwald 2022-04-18 13:00:34 +02:00
parent 12bb541f27
commit 9f51afa15f

37
main.go
View File

@ -4,6 +4,7 @@ import (
"bufio" "bufio"
"flag" "flag"
"fmt" "fmt"
"io"
"os" "os"
"regexp" "regexp"
"strconv" "strconv"
@ -25,6 +26,11 @@ var (
// they will be copied without any changes // they will be copied without any changes
keepUnmatched = flag.Bool("k", false, "keep unmatched lines") keepUnmatched = flag.Bool("k", false, "keep unmatched lines")
// if the amount of lines in stdin are not divisible by lineParseAmount,
// the last lines will be ignored completely.
// it may be useful to have a boolean flag for this behavior
lineParseAmount = flag.Int("n", 1, "amount of lines to feed into input pattern")
replacePattern = regexp.MustCompile(`\{(\d+)(?::(.*?))?\}`) replacePattern = regexp.MustCompile(`\{(\d+)(?::(.*?))?\}`)
) )
@ -36,8 +42,7 @@ func main() {
panic(err) panic(err)
} }
r := bufio.NewReader(os.Stdin) for line := range readLines(os.Stdin) {
for line, err := r.ReadString('\n'); err == nil; line, err = r.ReadString('\n') {
line = line[:len(line)-1] line = line[:len(line)-1]
matches := pattern.FindStringSubmatch(line) matches := pattern.FindStringSubmatch(line)
@ -52,6 +57,34 @@ func main() {
} }
} }
func readLines(r io.Reader) <-chan string {
ch := make(chan string, 10)
go func(out chan<- string, source io.Reader) {
defer close(out)
r := bufio.NewReader(source)
for {
var line string
var err error
lines := make([]string, 0, *lineParseAmount)
for line, err = r.ReadString('\n'); err == nil; line, err = r.ReadString('\n') {
lines = append(lines, line)
if len(lines) == cap(lines) {
break
}
}
if err != nil {
return
}
out <- strings.Join(lines, "")
}
}(ch, r)
return ch
}
func replaceVars(format string, vars ...string) string { func replaceVars(format string, vars ...string) string {
replacements := replacePattern.FindAllStringSubmatch(format, -1) replacements := replacePattern.FindAllStringSubmatch(format, -1)