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.
go-grep/main.go

59 lines
1.0 KiB

package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"github.com/fatih/color"
)
func check(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%s\n", err)
os.Exit(1)
}
}
func usage() {
fmt.Printf("Usage:\n\t %s [text] [file]", os.Args[0])
}
func main() {
var flagNoColor = flag.Bool("no-colour", false, "Disable color output")
flag.Parse()
if *flagNoColor {
color.NoColor = true
}
//set up colourful output
found := color.New(color.FgRed).PrintfFunc()
//check no args passed (min. two args need to be passed) and no more than 3
if len(os.Args) <= 2 || len(os.Args) > 3 {
usage() //print usage and then exit
os.Exit(1)
}
search := os.Args[1]
filename := os.Args[2]
fmt.Printf("search: %s\nfilename: %s\n\n", search, filename)
bytes, err := ioutil.ReadFile(filename)
check(err)
word := ""
//split []bytes into words by spaces
for i := 0; i < len(bytes); i++ {
word += string(bytes[i])
if string(bytes[i]) == " " {
fmt.Print(word)
word = ""
}
if word == search {
found("%s", word)
word = ""
}
}
}