= Go BufIO = The '''`bufio`''' package provides buffered I/O. <> ---- == Usage == === Reader === === Scanner === A `Scanner` is used to read a file in steps of 'tokens'. Calls to `Scan()` return the next token. A `SplitFunc` type function is used to tokenize a file. The default function splits a file into lines with line termination stripped. Scanning stops unrecoverably at EOF, an error, or a too-large token. If a more tolerant file reader is called for, use `Reader` instead. As an example: {{{ import ( "strings" "regexp" "bufio" "fmt" "os" ) var Pattern = regexp.MustCompile(`PING`) func main() { count := 0 // Initialize the Builder var content strings.Builder // Initialize the Scanner using STDIN scanner := bufio.NewScanner(os.Stdin) // Loop over scanned lines for scanner.Scan() { line := scanner.Text() matches := Pattern.FindAllStringIndex(line, -1) // Build lines for i := len(matches)-1; i >= 0; i-- { line = line[:matches[i][0]] + fmt.Sprintf("[%d]", count+i) + line[matches[i][1]:] } content.WriteString(line) content.WriteString("\n") count += len(matches) } // Check for scanner errors if err := scanner.Err(); err != nil { fmt.Println(err) } // Print to STDOUT fmt.Printf(content.String()) } }}} {{{ $ cat test Hello, this is PING your PING friend. I am PING testing your work. PING. PING PING PING test PING. $ cat test | ./scan-and-build Hello, this is [0] your [1] friend. I am [2] testing your work. [3]. [4] [5] [6] test [7]. }}} === Writer === ---- == See also == [[https://pkg.go.dev/bufio|bufio package]] ---- CategoryRicottone