从perl中的数组中获取变量

时间:2013-11-12 12:37:06

标签: linux perl

我正在运行以下命令并将4行作为输出。

userid@server:/home/userid# ps -ef|grep process

这是命令的输出。

userid  10117  9931  0 06:25 pts/0    00:00:00 grep process
userid  15329     1  0 Jul11 ?        00:03:40 process APP1
userid  15334 15329  1 Jul11 ?        2-00:40:53 process1 APP1
userid  15390 15334  0 Jul11 ?        05:19:31 process2 APP1

我想使用perl将值APP1保存到变量中。所以我想要一个类似$APP = APP1的输出。

4 个答案:

答案 0 :(得分:0)

尝试此操作(在这种情况下,您的输出位于文件in.txt中):

perl -ne ' /(APP\d+)/g; print "$1\n";' in.txt

打印:

APP1
APP1
APP1

答案 1 :(得分:0)

使用数组捕获的APPS1可能会有所帮助:

use strict;
use warnings;

my @apps;

while (<DATA>) {
    push @apps, $1 if /process\d*\s+(.+)/;
}

print "$_\n" for @apps;

__DATA__
userid  10117  9931  0 06:25 pts/0    00:00:00 grep process
userid  15329     1  0 Jul11 ?        00:03:40 process APP1
userid  15334 15329  1 Jul11 ?        2-00:40:53 process1 APP1
userid  15390 15334  0 Jul11 ?        05:19:31 process2 APP1

输出:

APP1
APP1
APP1

答案 2 :(得分:0)

APP1是命令行中的最后一个条目吗?或者,它是process*命令之后的第二个单词吗?

如果这是该行的最后一个,您可以使用:

use strict;
use warnings;
use autodie;

open my $command_output, "|-", "pgrep -fl process";
while ( my $command = < $command_output > ) {
    $command =~ /(\w+)$/;
    my $app = $1;  #The last word on the line...

否则,事情变得有点棘手。我使用pgrep代替ps -ef | grepps命令返回标题以及许多字段。你需要拆分它们,然后解析它们。此外,它甚至会向您显示用于获取您感兴趣的流程的grep命令。

带有pgrep-f参数的-l命令不返回标头,只返回进程ID,后跟完整命令。这使得使用正则表达式解析更容易。 (如果您不了解正则表达式,则需要learn关于它们。)

open my $command_output, "|-", "pgrep -fl process";
while ( my $command = < $command_output > ) {
    if ( not $process =~ /^\d+\s+process\w+\s+(\w+)/ ) {
        next;
    }
    my $app = $1;  #The second word in the returned command...

没有必要分裂或混乱。没有要跳过的标头正则表达式匹配数字进程ID,process命令,然后选择第二个单词。我甚至检查以确保pgrep的输出符合我的预期。否则,我会得到下一行。

答案 3 :(得分:0)

我使用单行命令来获得所需的结果。

#!/usr/bin/perl
use strict;
use warnings;
my $app1
$app1 = ( split /\s+/, `pgrep -f process1` )[-1];
print ($app1);