dup2.go 586 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. )
  7. func main() {
  8. counts := make(map[string]int)
  9. files := os.Args[1:]
  10. if len(files) == 0 {
  11. countLines(os.Stdin, counts)
  12. } else {
  13. for _, arg := range files {
  14. f, err := os.Open(arg)
  15. if err != nil {
  16. fmt.Fprintf(os.Stderr, "dup2: %v\n", err)
  17. continue
  18. }
  19. countLines(f, counts)
  20. f.Close()
  21. }
  22. }
  23. for line, n := range counts {
  24. if n > 1 {
  25. fmt.Printf("%d\t%s\n", n, line)
  26. }
  27. }
  28. }
  29. func countLines(f *os.File, counts map[string]int) {
  30. input := bufio.NewScanner(f)
  31. for input.Scan() {
  32. counts[input.Text()]++
  33. }
  34. }