Skip to content

Instantly share code, notes, and snippets.

@chinmay185
Created March 25, 2017 09:31
Show Gist options
  • Save chinmay185/c4438f638a143ab54afb8227a68a0043 to your computer and use it in GitHub Desktop.
Save chinmay185/c4438f638a143ab54afb8227a68a0043 to your computer and use it in GitHub Desktop.
Grep like command implementation in Go
package main
import (
"io/ioutil"
"os"
"log"
"bufio"
"fmt"
"strings"
"path/filepath"
"io"
"flag"
)
func main() {
sourceDir := flag.String("dir", "", "directory where to search")
fileType := flag.String("type", "", "type of files to search in")
textToSearch := flag.String("text", "", "text to search")
flag.Parse()
if *sourceDir == "" || *fileType == "" || *textToSearch == "" {
flag.PrintDefaults()
os.Exit(1)
}
allFiles, _ := ioutil.ReadDir(*sourceDir)
for _, f := range allFiles {
if !f.IsDir() && strings.HasSuffix(f.Name(), *fileType) {
//fmt.Println("searching file ", f.Name())
fullFilePath := filepath.Join(*sourceDir, f.Name())
file, err := os.Open(fullFilePath)
if err != nil {
log.Printf("Error reading %s", fullFilePath)
continue
}
func() {
defer file.Close()
searchText(file, *textToSearch)
}()
}
}
}
func searchText(rd io.Reader, textToSearch string) {
scanner := bufio.NewScanner(rd)
for scanner.Scan() {
if strings.Contains(scanner.Text(), textToSearch) {
fmt.Println(scanner.Text())
}
}
if err := scanner.Err(); err != nil {
log.Fatal("scanner error ", err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment