线过滤器是一种常见类型的程序,它读取stdin
上的输入,处理它,然后将一些派生结果打印到stdout
。grep
和sed
是常用的行过滤器。
这里是一个示例行过滤器,将写入所有输入文本转换为大写。可以使用此模式来编写自己的Go行过滤器。
所有的示例代码,都放在
F:\worksp\golang
目录下。安装Go编程环境请参考:/tutorial/detail-5562.html
line-filters.go
的完整代码如下所示 -
package main import ( "bufio" "fmt" "os" "strings" ) func main() { // Wrapping the unbuffered `os.Stdin` with a buffered // scanner gives us a convenient `Scan` method that // advances the scanner to the next token; which is // the next line in the default scanner. scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { // `Text` returns the current token, here the next line, // from the input. ucl := strings.ToUpper(scanner.Text()) // Write out the uppercased line. fmt.Println(ucl) } // Check for errors during `Scan`. End of file is // expected and not reported by `Scan` as an error. if err := scanner.Err(); err != nil { fmt.Fprintln(os.Stderr, "error:", err) os.Exit(1) } }
执行上面代码,将得到以下输出结果 -
F:\worksp\golang>go run line-filters.go this is a Line filters demo by zyiz.net THIS IS A LINE FILTERS DEMO BY zyiz.net yes YES No NO