field/main.go

35 lines
632 B
Go
Raw Permalink Normal View History

2024-05-22 21:36:15 +00:00
package main
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
func main() {
if len(os.Args) < 2 {
2024-05-22 21:41:30 +00:00
fmt.Fprintf(os.Stderr, "usage: %s <field-number>\n", os.Args[0])
2024-05-22 21:36:15 +00:00
os.Exit(1)
}
fieldNum, err := strconv.Atoi(os.Args[1])
if err != nil || fieldNum < 1 {
2024-05-22 21:41:30 +00:00
fmt.Fprintln(os.Stderr, "error: invalid field number")
2024-05-22 21:36:15 +00:00
os.Exit(1)
}
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
fields := strings.Fields(line)
if len(fields) >= fieldNum {
fmt.Println(fields[fieldNum-1])
}
}
if err := scanner.Err(); err != nil {
fmt.Fprintln(os.Stderr, "error reading input:", err)
}
}