Created
June 3, 2017 06:55
-
-
Save fpawel/a12bee63a26e04a847f8d6755be9e638 to your computer and use it in GitHub Desktop.
Count the line number of files in directory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"flag" | |
"fmt" | |
"io/ioutil" | |
"os" | |
"path/filepath" | |
) | |
func check(err error) { | |
if err != nil { | |
panic(err) | |
} | |
} | |
func main() { | |
var ext string | |
var searchDir string | |
flag.StringVar(&searchDir, "dir", "./", "directory path") | |
flag.StringVar(&ext, "ext", "", "file extension pattern") | |
flag.Parse() | |
fmt.Println("ext =", ext, "dir = ", searchDir) | |
count := 0 | |
err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error { | |
if err != nil { | |
fmt.Println("Error:", err, "path:", path) | |
} | |
if filepath.Ext(f.Name()) == ext { | |
fileBytes, err := ioutil.ReadFile(path) | |
check(err) | |
for _, ch := range fileBytes { | |
if ch == '\n' { | |
count++ | |
} | |
} | |
} | |
return nil | |
}) | |
if err != nil { | |
fmt.Println("Error:", err) | |
} | |
fmt.Println("COUNT:", count) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment