線過濾器是一種常見型別的程式,它讀取stdin
上的輸入,處理它,然後將一些派生結果列印到stdout
。grep
和sed
是常用的行過濾器。
這裡是一個範例行過濾器,將寫入所有輸入文字轉換為大寫。可以使用此模式來編寫自己的Go行過濾器。
所有的範例程式碼,都放在
F:\worksp\golang
目錄下。安裝Go程式設計環境請參考:/2/23/798.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 tw511.com
THIS IS A LINE FILTERS DEMO BY TW511.COM
yes
YES
No
NO