2017-02-17 64 views
3

我想用「的awk」來提取一個格式化的文件的具體信息,以便:AWK打印列,如果條件得到滿足

  1. 如果行有2場,第一列(100)被打印,並且第二列(2)表示跟隨的「X」對線對如果對應於NR +(2 * X -1)的行以「B」開始,則該行的第二列打印
  2. 如果NR +(2 * X -1)的相應行未以「B」開頭,則打印值爲「0」。

示例文件:

100 2 
A .5 .4 
.3 .2 .1  
B .9 .8 
.7 .6 .65 
200 1 
A .5 .4 
.3 .2 .1 

理想輸出:

100 .9 
200 0 

代碼迄今:

awk '{if(NF==2) print $1;}' 

主要生產:

100 
200 
+0

你應該表現出你已經嘗試過。 –

+0

我不是awk專家,但請在您的帖子中包含該信息。它會幫助有人決定如何幫助你。 –

回答

0

下面是一些awk代碼,以滿足您的要求:

代碼:

#!/bin/awk -f 
{ 
    # skip some lines if needed 
    if (to_skip-- > 0) next; 

    # if we don't have a header, keep the section number as record count 
    if (! have_header) { 
     header = $1; 
     have_header = 1 

     # skip some records 
     to_skip = $2 * 2 - 2; 
     next; 
    } 

    # if the first character is a 'B' get the second column  
    if ($1 == "B") 
     value = $2; 
    else 
     value = 0 

    # print the output, move to the next header 
    print header, value 
    have_header = 0; 
    to_skip = 1 
} 

輸出:

$ awk -f test.awk data.txt 
100 .9 
200 0 
4

輸入

$ cat f 
100 2 
A .5 .4 
.3 .2 .1  
B .9 .8 
.7 .6 .65 
200 1 
A .5 .4 
.3 .2 .1 

輸出

$ awk 'NF==2{t=$1; l=(NR+2*$2-1)}NR==l{print t,/^B/?$2:0}' f 
100 .9 
200 0 

說明

awk 'NF==2{     # If row has 2 fields 
      t=$1    # lets save 1st field and print later 
      l=(NR+2*$2-1)  # line to be checked 
    } 
    NR==l{   # if current record number is equal to l 

      # Print t, if starts with B then field 2 to be printed else 0 
      print t,/^B/?$2:0 
    } 
    ' f 
2
NF==2 {x=$1; rec=NR+2*$2-1} 
NR==rec {y=0; if ($1=="B") y=$2; print(x,y)} 
相關問題