douchenzhan3050 2016-03-05 19:52
浏览 239
已采纳

grep没有返回所有匹配的行

I can't figure out how to get grep to return all lines found in a file. It counts the correct number but only prints the last match.

$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;

Let's say self::$term = 'console.log'. It finds three matches in one particular file, which is correct (the term appears on lines 16, 21, and 31 of a test file), but $lines only prints: 31: console.log(response);.

What am I missing?

  • 写回答

1条回答 默认 最新

  • duanhuiqing9528 2016-03-05 20:41
    关注

    From php manual for exec:

    Return Values

    The last line from the result of the command. If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

    So you only get the last match that grep found, because it's the last line of output.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?