3
Go as a scripting language: lightweight, safe and fast
source link: https://yourbasic.org/golang/write-command-line-application/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Go as a scripting language: lightweight, safe and fast
yourbasic.org/golang
This example is a simplified version of the Unix grep
command.
The program searches the input file for lines containing the given pattern and prints these lines.
func main() {
log.SetPrefix("grep: ")
log.SetFlags(0) // no extra info in log messages
if len(os.Args) != 3 {
fmt.Printf("Usage: %v PATTERN FILE\n", os.Args[0])
return
}
pattern, err := regexp.Compile(os.Args[1])
if err != nil {
log.Fatalln(err)
}
file, err := os.Open(os.Args[2])
if err != nil {
log.Fatalln(err)
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if pattern.MatchString(line) {
fmt.Println(line)
}
}
if err := scanner.Err(); err != nil {
log.Println(err)
}
}
More code examples
Go blueprints: code for common tasks is a collection of handy code examples.
Share:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK