diff options
Diffstat (limited to 'shell/bin/grep.php')
-rw-r--r-- | shell/bin/grep.php | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/shell/bin/grep.php b/shell/bin/grep.php new file mode 100644 index 0000000..c73b911 --- /dev/null +++ b/shell/bin/grep.php @@ -0,0 +1,52 @@ +<?php
+class p_grep extends prog {
+ public static function flag($flags,$flag) {
+ return (strpos($flags,$flag)!==false);
+ }
+ public static function recurse_grep($pattern, $subject, $flags = '') {
+ // Do a breadth-first search
+ $dirs = array();
+ if ( is_dir($subject) ) {
+ $dirs[] = $subject;
+ } else {
+ self::grep($pattern, $subject, $flags);
+ }
+ foreach($dirs as $dir) {
+ $dh = opendir($dir);
+ while(false !== ( $file = readdir($dh)) ) {
+ if (( $file != '.' ) && ( $file != '..' )) {
+ self::recurse_grep($pattern, $subject.'/'.$file, $flags);
+ }
+ }
+ closedir($dh);
+ }
+ }
+
+ public static function grep($pattern, $file, $flags) {
+ $lines = preg_split("/\r\n/",file_get_contents($file));
+ foreach ($lines as $line_number => $line_contents) {
+ if (preg_match($pattern,$line_contents)>0) {
+ if (
+ (self::flag($flags,'r') && !self::flag($flags,'h')) // recursive
+ || (self::flag($flags,'H')) // or explicit
+ ) { echo htmlentities($file).': '; }
+ if (self::flag($flags,'n')) { echo $line_number.': '; }
+ echo htmlentities($line_contents)."\n";
+ }
+ }
+ }
+
+ public static function main($args, $env) {
+ $me = array_shift($args);
+ $flags = '';
+ while (substr($args[0],0,1) == '-') {
+ $flags .= array_shift($args);
+ }
+ $flags = preg_replace('/[ -]/','',$flags);
+ $pattern = array_shift($args);
+ foreach ($args as $file) {
+ if (self::flag($flags,'r')) { self::recurse_grep($pattern, $file, $flags); }
+ else { self::grep($pattern, $file, $flags); }
+ }
+ }
+}
|