package main import ( "fmt" "bufio" "os")func main() { counts := make(map[string]int) files :=os.Args[1:] // 接管命令上上的参数 fmt.Println(len(files)) if (len(files)) == 0 { countLine(os.Stdin,counts) } else { for _,arg :=range files { f,err :=os.Open(arg) //关上文件 if err != nil { fmt.Fprintf(os.Stderr,"dup2:%v\n",err) continue } countLine(f,counts) f.Close() } for line,n := range counts { if n>1 { fmt.Printf("%d\t%s\n",n,line) } } }}func countLine(f *os.File,counts map[string]int) { input := bufio.NewScanner(f) for input.Scan() { if input.Text() == "stop" {break} counts[input.Text()]++ } for line, n := range counts { if n > 1 { fmt.Printf("%d\t%s\n", n, line) } }}
创立 1.txt 2.txt
而后在 txt 文件中,输出字符串,得换行
windows 环境输出 go run ./main.go 1.txt 2.txt