Initial Version
pkg/grep/search.go:
package grep
import (
"bufio"
"os"
"regexp"
"strings"
)
func Grep(pattern string, filePath string) ([]string, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
var matchingLines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
match, err := regexp.MatchString(pattern, line)
if err != nil {
return nil, err
}
if match {
matchingLines = append(matchingLines, strings.TrimLeft(line, " \t"))
}
}
if err := scanner.Err(); err != nil {
return nil, err
}
return matchingLines, nil
}
regexp
package provides support for regular expressions. Regular expressions (regex or regexp) are patterns that describe sets of strings.
main.go:
package main
import (
"flag"
"fmt"
"log"
"github.com/Literank/gorep/pkg/grep"
)
func main() {
flag.Parse()
// Retrieve positional arguments
// pattern - The pattern to search for
// file_path - The path to the file to search in
args := flag.Args()
if len(args) < 2 {
log.Fatal("Both pattern and file_path are required")
}
result, err := grep.Grep(args[0], args[1])
if err != nil {
log.Fatal(err)
}
for _, line := range result {
fmt.Println(line)
}
}
flag
package provides a convenient way to define and parse command-line arguments, including both flags and positional arguments.
It's a standard library package that simplifies the process of handling command-line input for your programs.
Run the program like this:
# search "result" in file main.go
go run main.go result main.go
You will get result lines like below:
result, err := grep.Grep(args[0], args[1])
for _, line := range result {