2013-02-19 86 views
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的新手。如何获得所需的输出?

回答

2

可以使用-n选项以一衬垫来处理标准输入通过管道发送:

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

这是简单地在正则表达式/\s*=\s*/分裂(-a),这将分割上等号和条周围有空白。当找到目标文本时,它会打印第二个字段,该字段应该是您的字符串。

+0

哇我知道了,谢谢很多人@TLP,我只想知道我们如何嵌入脚本中,因为这是一个命令行的东西,在那里我可以找到这些文本处理东西的一些例子 – mviswa 2013-02-22 06:48:55

+0

“剧本”?那是什么脚本?如果你愿意,可以用'-MO = Deparse'开关来查看完整的代码。 – TLP 2013-02-22 07:24:44

0

你可以在开放使用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"; 
} 
+0

我对shell感到满意,实际上这是一个已经在我们的prod服务器上运行的脚本,没有任何问题,我正在学习如何在Perl中保留shell本机命令。谢谢你的时间,我欣赏它 – mviswa 2013-02-22 06:50:34

1

对此的解决方案是this answer只有轻微的修改。基本上,您需要每行以“数据库别名”开头的第四列。您可以使用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遍历文件去过滤掉非即时匹配线。这种方法不会将整个文件存储在内存中。