2013-02-19 94 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遍歷文件去過濾掉非即時匹配線。這種方法不會將整個文件存儲在內存中。