строковые фильтры

This commit is contained in:
badkaktus 2019-10-11 13:57:05 +03:00
parent 3e4828bcb4
commit f29db8867b
3 changed files with 22 additions and 20 deletions

View File

@ -57,7 +57,7 @@ Epoch
Кодирование Base64 (Base64 Encoding) Кодирование Base64 (Base64 Encoding)
Чтение файлов (Reading Files) Чтение файлов (Reading Files)
Запись файлов (Writing Files) Запись файлов (Writing Files)
Line Filters Строковые фильтры (Line Filters)
File Paths File Paths
Directories Directories
Temporary Files and Directories Temporary Files and Directories

View File

@ -1,11 +1,13 @@
// A _line filter_ is a common type of program that reads // _Строковый фильтр_ - это типичный тип программы,
// input on stdin, processes it, and then prints some // которая читает входные данные в stdin, обрабатывает
// derived result to stdout. `grep` and `sed` are common // их и затем выводит некоторый производный результат в
// line filters. // стандартный вывод. `grep` и `sed` - это обычные строковые
// фильтры.
// Here's an example line filter in Go that writes a // Вот пример строкового фильтра в Go, который записывает
// capitalized version of all input text. You can use this // заглавную версию всего входного текста. Вы можете
// pattern to write your own Go line filters. // использовать этот шаблон для написания ваших собственных
// фильтров Go.
package main package main
import ( import (
@ -17,23 +19,23 @@ import (
func main() { func main() {
// Wrapping the unbuffered `os.Stdin` with a buffered // Обертывание небуферизованного `os.Stdin` буферизованным
// scanner gives us a convenient `Scan` method that // сканером дает нам удобный метод сканирования `Scan`,
// advances the scanner to the next token; which is // который продвигает сканер к следующему токену; который
// the next line in the default scanner. // является следующей строкой в сканере по умолчанию.
scanner := bufio.NewScanner(os.Stdin) scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() { for scanner.Scan() {
// `Text` returns the current token, here the next line, // `Text` возвращает текущий токен, из ввода - на
// from the input. // следующую строку.
ucl := strings.ToUpper(scanner.Text()) ucl := strings.ToUpper(scanner.Text())
// Write out the uppercased line. // Печатает в верхнем регистре.
fmt.Println(ucl) fmt.Println(ucl)
} }
// Check for errors during `Scan`. End of file is // Проверяем ошибки для `Scan`. Ожидается конец файла,
// expected and not reported by `Scan` as an error. // и он не сообщается методом `Scan` как ошибка.
if err := scanner.Err(); err != nil { if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error:", err) fmt.Fprintln(os.Stderr, "error:", err)
os.Exit(1) os.Exit(1)

View File

@ -1,9 +1,9 @@
# To try out our line filter, first make a file with a few # Чтобы опробовать наш фильтр строк, сначала создайте
# lowercase lines. # файл с несколькими строчными строчками.
$ echo 'hello' > /tmp/lines $ echo 'hello' > /tmp/lines
$ echo 'filter' >> /tmp/lines $ echo 'filter' >> /tmp/lines
# Then use the line filter to get uppercase lines. # Затем используйте фильтр строк, чтобы получить строчные буквы.
$ cat /tmp/lines | go run line-filters.go $ cat /tmp/lines | go run line-filters.go
HELLO HELLO
FILTER FILTER