線過(guò)濾器是一種常見(jiàn)類型的程序,它讀取stdin上的輸入,處理它,然后將一些派生結(jié)果打印到stdout。grep和sed是常用的行過(guò)濾器。
這里是一個(gè)示例行過(guò)濾器,將寫入所有輸入文本轉(zhuǎn)換為大寫。可以使用此模式來(lái)編寫自己的Go行過(guò)濾器。
所有的示例代碼,都放在
F:\worksp\golang目錄下。安裝Go編程環(huán)境請(qǐng)參考:http://www.yiibai.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)
}
}
執(zhí)行上面代碼,將得到以下輸出結(jié)果 -
F:\worksp\golang>go run line-filters.go
this is a Line filters demo by yiibai.com
THIS IS A LINE FILTERS DEMO BY YIIBAI.COM
yes
YES
No
NO