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.

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

报告相同问题?

悬赏问题

  • ¥15 我想在一个软件里添加一个优惠弹窗,应该怎么写代码
  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流