我怎样才能获得所需的输出?

时间:2013-02-19 07:27:42

标签: perl

System Database Directory

 Number of entries in the directory = 3

Database 1 entry:

 Database alias                       = Sample
 Database name                        = sample
 Local database directory             = /home/db2inst1
 Database release level               = b.00
 Comment                              =
 Directory entry type                 = Indirect
 Catalog database partition number    = 0
 Alternate server hostname            =
 Alternate server port number         =

Database 2 entry:

 Database alias                       = sample2
 Database name                        = sample2
 Local database directory             = /home/db2inst1
 Database release level               = b.00
 Comment                              =
 Directory entry type                 = Indirect
 Catalog database partition number    = 0
 Alternate server hostname            =
 Alternate server port number         =

Database 3 entry:

 Database alias                       = sample3
 Database name                        = sample
 Local database directory             = /home/db2inst1
 Database release level               = b.00
 Comment                              =
 Directory entry type                 = Indirect
 Catalog database partition number    = 0
 Alternate server hostname            =
 Alternate server port number         =

执行系统命令时,我有以下文字。我只想要sample,sample2,sample3作为输出。我熟悉shell中的这个,但我是perl的新手。

3 个答案:

答案 0 :(得分:2)

您可以在单行中使用-n选项来处理通过管道发送的stdin:

yourcommand | perl -F'\s*=\s*' -anlwe '/Database alias/ && print $F[1]' 

这只是正则表达式-a上的一个分割(/\s*=\s*/),它将在等号上分割并剥离周围的空格。找到目标文本后,它会打印第二个字段,该字段应该是您的字符串。

答案 1 :(得分:1)

对此的解决方案只是this answer的轻微修改。基本上,您希望每行的第四列以“Database alias”开头。您可以使用perl grep函数选择匹配的行,然后执行上述solution中的选择:

#!/usr/bin/env perl

use strict;
use warnings;

my $file = shift;
my @aliases;

open FILE, $file or die "Cannot open input file";

chomp (my @lines = grep /^Database alias/, <FILE>);    

close FILE;

for my $row (@lines) {                
    my @columns = split /\s+/, $row;  
    push @aliases, $columns[3];
}

print join "\n", @aliases;

如果您的输入文件很大,我建议您使用while循环浏览该文件,并即时过滤掉不匹配的行。这种方法不会将整个文件存储在内存中。

答案 2 :(得分:0)

你可以在open中使用shell命令:

open(IN,"cmd_that_generate_the_output|grep -i 'Database alias'|cut -f2 -d'='|cut -f2 -d' '|") or die;
while (my $str = <IN>){
  print "str: $str\n";
}