Added "in" utility.

This commit is contained in:
Andrey Parhomenko 2022-11-14 19:15:02 +05:00
parent f492bfeea9
commit 1ee7ad4080
3 changed files with 77 additions and 1 deletions

View file

@ -1,4 +1,4 @@
Copyright (c) 2020 k1574
Copyright (c) 2020 surdeus, aka Andrey Parhomenko
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View file

@ -23,6 +23,7 @@ import(
"github.com/surdeus/goblin/src/tool/wc"
"github.com/surdeus/goblin/src/tool/ftest"
"github.com/surdeus/goblin/src/tool/grange"
"github.com/surdeus/goblin/src/tool/in"
)
func main() {
@ -48,6 +49,7 @@ func main() {
"wc" : mtool.Tool{wc.Run, "count words, bytes, runes etc"},
"ftest" : mtool.Tool{ftest.Run, "filter files by specified features"},
"range" : mtool.Tool{grange.Run, "too lazy"},
"in" : mtool.Tool{in.Run, "filter strings from stdin that aren not in arguments"},
}
mtool.Main("goblin", tools)

74
src/tool/in/main.go Normal file
View file

@ -0,0 +1,74 @@
package in
import (
"os"
"io"
"bufio"
"fmt"
"flag"
)
func Run(args []string) {
var (
print bool
not bool
)
arg0 := args[0]
args = args[1:]
flagSet := flag.NewFlagSet(arg0, flag.ExitOnError)
flagSet.BoolVar(&print, "p", false, "print matching lines")
flagSet.BoolVar(&not, "n", false, "find not matching lines")
flagSet.Usage = func() {
fmt.Fprintf(os.Stderr, "usage: %s <str1> [str2, ...str3]\n", arg0)
flagSet.PrintDefaults()
os.Exit(1)
}
flagSet.Parse(args)
args = flagSet.Args()
if len(args) == 0 {
flagSet.Usage()
}
mp := make(map[string] int)
for _, v := range args {
mp[v] = 0
}
status := 1
r := bufio.NewReader(os.Stdin)
if not {
status = 0
}
for {
l, err := r.ReadString('\n')
if err == io.EOF {
break
}
if len(l) != 0 && l[len(l)-1] == '\n' {
l = l[:len(l)-1]
}
_, ok := mp[l]
if not {
if ok {
status = 1
ok = false
} else {
ok = true
}
} else {
if ok {
status = 0
}
}
if print && ok {
fmt.Println(l)
}
}
os.Exit(status)
}