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 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用