线过滤器是一种常见类型的程序,它读取stdin
上的输入,处理它,然后将一些派生结果打印到stdout
。grep
和sed
是常用的行过滤器。
这里是一个示例行过滤器,将写入所有输入文本转换为大写。可以使用此模式来编写自己的go行过滤器。
所有的示例代码,都放在
f:\worksp\golang
目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.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 h3.com
this is a line filters demo by h3.com
yes
yes
no
no