2010-11-02 26 views
4

我有以下問題,也許你可以幫幫忙:AWK捕獲文本進入下一行

我想匹配的文字是這樣的:

Data Generated using Turbine's method 
Stuff 
more Stuff 
Full speed : 0.87 
Data generated using My method 
Stuff 
more stuff 
Full speed : 0.96 

Data Generated using Turbine's method 
Stuff 
more Stuff 
Full speed : 0.83 
Data generated using My method 
Stuff 
more stuff 
Full speed : 0.94 

我想匹配的行包含全速並將它們輸出到如下表格中:

Turbine's My 
0.87 0.96 
0.83 0.94 

所以我可以比較兩種方法。但是我有麻煩awk來匹配我目前正則表達式是:

/Data Generated using Turbine's method.*Full speed/ 
/Data Generated using My method.*Full speed/ 

什麼是我的問題是什麼呢?爲什麼不awk匹配呢?

感謝您的意見

+1

只要你就會知道,在你嘗試正則表達式 「d *」 表示 「零個或多個d」。你會想''*'這意味着「零或更多的任何字符」(但這並不能解決多行問題)。 – 2010-11-02 15:56:59

回答

2

試試這個:

awk -F: 'BEGIN {OFS="\t"; print "Turbine\047s" OFS "My"} /Turbine/ {tflag=1; mflag=0} /My/ {mflag=1; tflag=0} /Full speed/ {if (tflag) {T=$2; tflag=0}; if (mflag) { print T OFS OFS $2; mflag=0}}' inputfile 

在獨立線路:

awk -F: 'BEGIN {OFS="\t"; print "Turbine\047s" OFS "My"} 
     /Turbine/ {tflag=1; mflag=0} 
     /My/ {mflag=1; tflag=0} 
     /Full speed/ { 
      if (tflag) {T=$2; tflag=0}; 
      if (mflag) { print T OFS OFS $2; mflag=0}}' inputfile 

或者一個稍微簡單的版本:

awk -F: '/Turbine/, /^Full speed/ {if ($0 ~ /Full/) T=$2} 
     /My/, /^Full speed/ {if ($0 ~ /Full/) print T, $2}' 
+0

我跟着這個版本去了,因爲它最終融入我的腳本更簡單。謝謝。實際上〜操作員做了什麼? – tarrasch 2010-11-04 10:28:31

+0

這是正則表達式匹配運算符:'string〜regex' - http://www.gnu.org/manual/gawk/gawk.html#Using-Constant-Regexps – 2010-11-04 13:50:51

3

AWK中的單個RE只會嘗試匹配一條線。你似乎想要一個範圍模式,如:/^Data Generated/, /^Full Speed.*$/

編輯:準確地找到你要求的格式是相對困難。如果你不介意側身把它,可以這麼說,所以每個組是在一條線上,而不是在一列,它變得相當簡單:

/^Data/  { name = $4; } 
/^Full/  { speeds[name] = speeds[name] " " $4; } 

END { 
    for (i in speeds) 
     printf("%10s : %s\n", i, speeds[i]); 
} 
+0

謝謝,抓住線。甚至不知道這些存在。如果你能告訴我如何匹配全速後面的數字,那麼這將是完美的 – tarrasch 2010-11-02 15:45:18

+0

你是什麼意思'全速後面?' $ 4是你匹配時的數字^ ^完整/ – JimR 2010-11-02 18:21:31

+0

@JimR:他的評論早於編輯,所以他只評論一個範圍的使用(如果我更多地閱讀他的問題,我可能不會建議小心地開始)。 – 2010-11-02 18:25:14

0

我會用Perl:

perl -ne ' 
    if (/(\S+) method/) {$method = $1} 
    if (/Full speed : ([\d.]+)/) {push @{$speeds{$method}}, $1} 
    END { 
     @keys = keys %speeds; 
     print join("\t", @keys), "\n"; 
     $max = 0; 
     for $v (values %speeds) { 
      $len = scalar @$v; 
      $max = $len if $len > $max; 
     } 
     for $i (0 .. $max-1) { 
      for $k (@keys) {print $speeds{$k}[$i], "\t"}; 
      print "\n"; 
     } 
    } 
' speed.txt 

其輸出

My  Turbine's 
0.96 0.87 
0.94 0.83 
+0

不用感謝它的一個更大的awk腳本的所有部分,但無論如何感謝 – tarrasch 2010-11-04 10:24:23