[英]how to print stuff in a loop to console, so that unix grep can interact with it?
How to print stuff in a loop to console, so that UNIX grep can interact with it ? 如何将循环中的东西打印到控制台,以便UNIX grep可以与它进行交互? I made a console php tool for parsing some data.
我制作了一个用于解析一些数据的控制台php工具。 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 "\n";
}
}
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. 我想用Unix grep命令与这个打印数据进行交互。 For example:
例如:
php script.php -list | php script.php -list | grep stuff
grep的东西
Using this code all data gets printed in the console, but grep can not filter it, why? 使用此代码,所有数据都会在控制台中打印出来,但是grep无法对其进行过滤,为什么? how to make grep filter the text ?
如何让grep过滤文本?
Consider this demonstration: 考虑这个演示:
<?php
$words = array( "column", "igloo", "magenta", "turnip", "adlib", "stuff");
foreach( $words as $word){
printf("%8s\n", $word );
}
We can filter out the line containing stuff
just fine. 我们可以过滤掉包含
stuff
的行。
$ php ./t.php | grep 'stuff'
stuff
If instead we write to stderr
, we must filter a bit diferently: 如果我们写入
stderr
,我们必须过滤掉一点:
<?php
$words = array( "column", "igloo", "magenta", "turnip", "adlib", "stuff");
foreach( $words as $word){
fprintf(STDERR,"%8s\n", $word );
}
Since grep
reads from stdin, we need to make sure we redirect stderr
to stdout
: 由于
grep
从stdin读取,我们需要确保将stderr
重定向到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: 最后,如果你想确保你没有得到
stdout
,你可以切换它们:
php ./t.php 2>&1 1>&2 | grep stuff
Or just discard the data originally written to stdout: 或者只是丢弃最初写入stdout的数据:
php ./t.php 2>&1 >/dev/null | grep stuff
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.