Skip to content

Instantly share code, notes, and snippets.

@Burgestrand
Created November 15, 2009 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Burgestrand/235275 to your computer and use it in GitHub Desktop.
Save Burgestrand/235275 to your computer and use it in GitHub Desktop.
Count the total number of lines in files in a directory.
#!/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