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.

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

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料