0
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 新手。

4

3 回答 3

2

您可以使用-n单行中的选项来处理通过管道发送的标准输入:

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

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

于 2013-02-19T08:33:06.467 回答
1

对此的解决方案只是对这个答案稍作修改。基本上,您希望每行的第四列以“数据库别名”开头。您可以使用 perlgrep函数选择匹配行,然后从上述解决方案中执行选择:

#!/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循环遍历文件并即时过滤掉不匹配的行。这种方法不会将整个文件存储在内存中。

于 2013-05-23T15:01:41.360 回答
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";
}
于 2013-02-19T09:03:03.207 回答