This is an education project that attempts to reimplement the GNU coreutils in Go. You can find the full manual here:
https://www.gnu.org/software/coreutils/manual/coreutils.html
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
772 B
53 lines
772 B
|
1 week ago
|
package main
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"regexp"
|
||
|
|
"os"
|
||
|
|
"bufio"
|
||
|
|
"flag"
|
||
|
|
"log"
|
||
|
|
"io"
|
||
|
|
)
|
||
|
|
|
||
|
|
func ScanInput(input io.Reader, exp string, prefix string) {
|
||
|
|
scan := bufio.NewScanner(input)
|
||
|
|
re, err := regexp.Compile(exp)
|
||
|
|
|
||
|
|
if err != nil { log.Fatal(err) }
|
||
|
|
|
||
|
|
for scan.Scan() {
|
||
|
|
line := scan.Text()
|
||
|
|
|
||
|
|
if re.MatchString(line) {
|
||
|
|
if prefix != "" {
|
||
|
|
fmt.Print(prefix, ": ")
|
||
|
|
}
|
||
|
|
|
||
|
|
fmt.Println(line)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func main() {
|
||
|
|
flag.Parse()
|
||
|
|
|
||
|
|
args := flag.Args()
|
||
|
|
|
||
|
|
if len(args) == 0 {
|
||
|
|
log.Fatal("USAGE: grep <regex> [files...]")
|
||
|
|
} else if len(args) == 1 {
|
||
|
|
ScanInput(os.Stdin, args[0], "")
|
||
|
|
} else {
|
||
|
|
exp := args[0]
|
||
|
|
files := args[1:]
|
||
|
|
|
||
|
|
for _, file := range files {
|
||
|
|
input, err := os.Open(file)
|
||
|
|
if err != nil { log.Fatal(err) }
|
||
|
|
|
||
|
|
ScanInput(input, exp, file)
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|