This is a creation in Article, where the information may have evolved or changed.
Program Name
Countline
OS package to get running parameters
Run the time to provide two parameters, one is the directory, one is the extension
Such as:
countline . go
Exit the program without running parameters
iflen(os.Args) != 3 { fmt.Println("countline [Dir] [extention]") return }
How many ' \ n ' files are calculated
funcstringint64, err error) { fmt.Println("count file:", name) data, err := ioutil.ReadFile(name) ifnil { return } count = 0 for i := 0len(data); i++ { if'\n' { count++ } } fmt.Println("line:", count) return}
Traverse Directory
filepath.Walk(os.Args[1funcstring, info os.FileInfo, err error) error { if getExt(path) == os.Args[2] { fmt.Println(path) n, e := countFileLine(path) ifnil { fmt.Println("lines: ", n) sum = sum + n } } returnnil })
FilePath. Walk the second member is a function, where path is the path of the file that is traversed, and it is read directly after judging that it is a file.
Full code:
PackageMainImport("FMT" "Io/ioutil" "OS" "Path/filepath" "Strings")var(SumInt64)funcMain () {if Len(OS. Args)! =3{FMT. Println ("Countline [Dir] [extention]")return} filepath. Walk (OS. Args[1],func(Pathstring, Info OS. FileInfo, err Error) error {ifGetext (path) = = OS. Args[2] {FMT. PRINTLN (path) n, E: = Countfileline (path)ifE = =Nil{FMT. Println ("lines:", n) sum = SUM + n}}return Nil}) fmt. Println ("Total lines:", sum)}//Get the file extension, last. What followsfuncGetext (fstring) (extstring) {//FMT. PRINTLN ("ext:", f)Index: = strings. LastIndex (F,".") Data: = []byte(f) forI: = index +1; I <Len(data); i++ {ext = ext +string([]byte{Data[i]}) }return}funcCountfileline (namestring) (CountInt64, err Error) {FMT. Println ("Count file:", name) data, err: = Ioutil. ReadFile (name)ifErr! =Nil{return} count =0 forI: =0; I <Len(data); i++ {ifData[i] = =' \ n '{count++}} Fmt. Println ("line:", count)return}