Concise Go Text Transformation Program

GolangGolangBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

The Line Filters lab is a common type of program that reads input on stdin, processes it, and then prints some derived result to stdout. The purpose of this lab is to write a Go program that reads input text and modifies it according to specific requirements.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL go(("`Go`")) -.-> go/FileOperationsGroup(["`File Operations`"]) go/FileOperationsGroup -.-> go/line_filters("`Line Filters`") subgraph Lab Skills go/line_filters -.-> lab-15486{{"`Concise Go Text Transformation Program`"}} end

Line Filters

The problem to be solved in this lab is to write a Go program that reads input text from stdin, capitalizes all the letters in the text, and then prints the modified text to stdout.

  • The program must read input text from stdin.
  • The program must capitalize all the letters in the input text.
  • The program must print the modified text to stdout.
## To try out our line filter, first make a file with a few
## lowercase lines.
$ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines

## Then use the line filter to get uppercase lines.
$ cat /tmp/lines | go run line-filters.go
HELLO
FILTER

There is the full code below:

// A _line filter_ is a common type of program that reads
// input on stdin, processes it, and then prints some
// derived result to stdout. `grep` and `sed` are common
// line filters.

// Here's an example line filter in Go that writes a
// capitalized version of all input text. You can use this
// pattern to write your own Go line filters.
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)
	}
}

Summary

The Line Filters lab requires writing a Go program that reads input text from stdin, capitalizes all the letters in the text, and then prints the modified text to stdout. This lab is a great way to practice writing Go programs that read and modify input text.

Other Golang Tutorials you may like