douba8048 2014-03-22 22:17
浏览 37
已采纳

如何在循环中打印东西到控制台,以便unix grep可以与它交互?

How to print stuff in a loop to console, so that UNIX grep can interact with it ? I made a console php tool for parsing some data. I am in need of printing some data to console.

public function printAlerts()
{
    $alertLinks = $this->parser->alertLinks($this->mc->listAlerts());

    $idSize = $alertLinks['sizeArray']['id'];
    $dateSize = $alertLinks['sizeArray']['date'];
    $nameSize = $alertLinks['sizeArray']['name'];

    $margin = 5;

    foreach ($alertLinks['alertArray'] as $alert)
    {
        $this->printColumn($alert['id'], $idSize, $margin);
        $this->printColumn($alert['date'], $dateSize, $margin);
        $this->printColumn($alert['name'], $nameSize, $margin);
        echo "
";
    }
}

private function printColumn($data, $space = 0, $margin = 0)
{
    echo $data;
    $len = ($space - strlen($data)) + $margin;

    for ($i = 0; $i < $len; $i++)
    {
        echo ' ';
    }

    return;
}

I would like to interact with this printed data with Unix grep command. For example:

php script.php -list | grep stuff

Using this code all data gets printed in the console, but grep can not filter it, why? how to make grep filter the text ?

  • 写回答

1条回答 默认 最新

  • dooso0594 2014-03-22 22:25
    关注

    Consider this demonstration:

    <?php
    $words = array( "column", "igloo", "magenta", "turnip", "adlib", "stuff");
    
    foreach( $words as $word){
            printf("%8s
    ", $word );
    }
    

    We can filter out the line containing stuff just fine.

    $ php ./t.php | grep 'stuff'
       stuff
    

    If instead we write to stderr, we must filter a bit diferently:

    <?php
    $words = array( "column", "igloo", "magenta", "turnip", "adlib", "stuff");
    
    foreach( $words as $word){
            fprintf(STDERR,"%8s
    ", $word );
    }
    

    Since grep reads from stdin, we need to make sure we redirect stderr to stdout:

    php ./t.php 2>&1 | grep stuff
    

    Finally, if you want to make sure you don't get stdout too, you could switch them:

    php ./t.php 2>&1 1>&2 | grep stuff
    

    Or just discard the data originally written to stdout:

    php ./t.php 2>&1 >/dev/null | grep stuff
    

    Hope it helps!

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

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等