簡體   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