繁体   English   中英

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

[英]how to print stuff in a loop to console, so that unix grep can interact with it?

如何将循环中的东西打印到控制台,以便UNIX grep可以与它进行交互? 我制作了一个用于解析一些数据的控制台php工具。 我需要将一些数据打印到控制台。

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 "\n";
    }
}

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

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

    return;
}

我想用Unix grep命令与这个打印数据进行交互。 例如:

php script.php -list | grep的东西

使用此代码,所有数据都会在控制台中打印出来,但是grep无法对其进行过滤,为什么? 如何让grep过滤文本?

考虑这个演示:

<?php
$words = array( "column", "igloo", "magenta", "turnip", "adlib", "stuff");

foreach( $words as $word){
        printf("%8s\n", $word );
}

我们可以过滤掉包含stuff的行。

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

如果我们写入stderr ,我们必须过滤掉一点:

<?php
$words = array( "column", "igloo", "magenta", "turnip", "adlib", "stuff");

foreach( $words as $word){
        fprintf(STDERR,"%8s\n", $word );
}

由于grep从stdin读取,我们需要确保将stderr重定向到stdout

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

最后,如果你想确保你没有得到stdout ,你可以切换它们:

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

或者只是丢弃最初写入stdout的数据:

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

希望能帮助到你!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM