使用Perl接受命令输入

时间:2018-11-14 01:41:34

标签: linux perl debian

我在Perl读取命令输出时遇到麻烦。

有问题的命令:ps | grep |

我正在尝试执行如下脚本:

ps  | grep  | script.pl

其中“ ps | grep |”的输出将用作脚本的输入,以打印出状态及其相应的命令。

输出:

0    command1
1    command2
....

我知道在bash中,您可以使用“ $#”来访问要用作输入的参数。 其中#对应于其在命令行中的位置。 Perl毫无头绪。

1 个答案:

答案 0 :(得分:4)

<><ARGV>的缩写。 ARGV是一个神奇的句柄,它从@ARGV元素命名的文件中读取,或者如果STDIN为空(从这里开始),则从@ARGV中读取。因此,您所需要做的就是使用<>阅读。

例如,

#!/usr/bin/perl

use strict;
use warnings qw( all );

while (<>) {
   chomp;
   print "Got <$_>\n";
}

输出:

$ ps aux | grep pts | ./script.pl
Got <ikegami  22570  0.0  0.0 101028  3460 ?        S    Nov07   0:02 sshd: ikegami@pts/2 >
Got <ikegami  22571  0.0  0.0 129928  3456 pts/2    Ss   Nov07   0:00 -bash>
Got <ikegami  22865  0.0  0.0 127240  2432 pts/2    R+   18:12   0:00 ps aux>
Got <ikegami  22866  0.0  0.0 120540  2160 pts/2    S+   18:12   0:00 grep pts>
Got <ikegami  22867  0.0  0.0 129604  3928 pts/2    R+   18:12   0:00 /usr/bin/perl ./script.pl>

剩下的就是从读取的数据中提取所需的信息。当然,您可以简单地使用

ps ah -o tty,command
相关问题