Created
November 15, 2009 15:17
-
-
Save Burgestrand/235275 to your computer and use it in GitHub Desktop.
Count the total number of lines in files in a 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
#!/usr/bin/env php | |
<?php | |
// Konfiguration | |
$dir = NULL; // Mapp du vill räkna rader ur | |
$verbose = TRUE; // visa antal rader för varje fil | |
/* Arbetande kod | |
-------------------------------------------------------------------------*/ | |
$path = isset($argv[1]) ? $argv[1] : (is_null($dir) ? '.' : $dir); | |
$path = realpath($path); | |
// Gå igenom varje mapp rekursivt | |
$iter = new RecursiveDirectoryIterator($path); | |
$iiter = new RecursiveIteratorIterator($iter); | |
$files = array(); | |
foreach ($iiter as $filename => $obj) | |
{ | |
$files[$filename] = countLines($filename); | |
} | |
// Visa lite extra info | |
if ($verbose) | |
{ | |
asort($files, SORT_NUMERIC); | |
array_map('show', array_keys($files), array_values($files)); | |
println(); | |
} | |
// Summan av antalet rader | |
$sumlines = array_reduce($files, 'add', 0); | |
println("{$path}: {$sumlines} rader."); | |
/* Hjälpfunktioner | |
-------------------------------------------------------------------------*/ | |
function countLines($filepath) | |
{ | |
$fp = fopen($filepath, 'r'); | |
$n = 0; | |
while (fgets($fp)) { ++$n; } | |
fclose($fp); | |
return $n; | |
} | |
function println($str = "") | |
{ | |
print $str . "\n"; | |
} | |
function show($path, $n = 0) | |
{ | |
println("{$n}\t{$path}"); | |
} | |
function add($x = 0, $y = 0) | |
{ | |
return $x + $y; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment