2016-03-05 149 views
0

我无法弄清楚如何让grep返回文件中找到的所有行。它计算正确的数字,但只打印最后一场比赛。grep不返回所有匹配行

$found = array(); 
$term = escapeshellarg(self::$term); 
foreach(self::$files as $file) 
{ 
    if($count = exec("grep -i -c ".$term." ".$file)) 
    { 
     $lines = exec("grep -i -n ".$term." ".$file); 
     $found[] = array('count'=>$count,'lines'=>$lines,'file'=>str_replace(self::$dir, '', $file)); 
    } 
} 
self::$files = $found; 

比方说self::$term = 'console.log'。它在一个特定文件中找到三个匹配,这是正确的(该术语出现在测试文件的第16,21和31行),但$lines仅打印:31: console.log(response);

我错过了什么?

回答

1

php manual为高管:

返回值

从命令结果的最后一行。如果您需要执行 命令并将命令中的所有数据直接传回 而不受任何干扰,请使用passthru()函数。

所以你只能得到grep找到的最后一个匹配,因为它是最后一行输出。

+0

有没有其他的选择,因为passthru()似乎回应结果? –

+0

没关系。使用'ob_start()','$ lines = ob_get_content()'和'ob_end_clean()'是我需要做的。谢谢! –