Go programming example [command line filter]

read catalog

A line filter is a common function in programs that read input from the standard input stream, process that input, and then output some result to standard output.

grepand sedare common row filters.

Here is an example line filter written in Go that converts all input text to uppercase.
You can use this pattern to write your own Go line filters.

// line-filters.go
package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
)

func main() {
    
    

	// 对 `os.Stdin` 使用一个带缓冲的 scanner,
	// 让我们可以直接使用方便的 `Scan` 方法来直接读取一行,
	// 每次调用该方法可以让 scanner 读取下一行。
	scanner := bufio.NewScanner(os.Stdin)

	for scanner.Scan() {
    
    
		// `Text` 返回当前的 token,现在是输入的下一行。
		ucl := strings.ToUpper(scanner.Text())

		// 写出大写的行。
		fmt.Println(ucl)
	}

	// 检查 `Scan` 的错误。文件结束符是可以接受的,并且
	// 不会被 `Scan` 当作一个错误。
	if err := scanner.Err(); err != nil {
    
    
		fmt.Fprintln(os.Stderr, "error:", err)
		os.Exit(1)
	}
}

To try out our line filter, first create a file with lowercase lines.

[root@bogon test]# echo '1行' > writing-files.txt
[root@bogon test]# echo '2行' >> writing-files.txt
[root@bogon test]# echo '3行' >> writing-files.txt

[root@bogon test]# cat writing-files.txt 
1行
2行
3行
[root@bogon test]# cat writing-files.txt  | go run main.go 
1行
2行
3行
[root@bogon test]# 

Guess you like

Origin blog.csdn.net/weiguang102/article/details/129874859