2017-03-23 86 views
0

使用我的有限腳本知識..我已經將一個期望腳本放在一起,在特定設備上運行一些命令。輸出如下,並從所有設備保存到一個文件(我剛剛列出2個設備作爲示例)。AWK - 匹配多個圖案並在一行中打印結果

Current State : Active 
Router1slot1# showstats 
    Active stats    : 31 
    Active stats1   : 47 
Router1slot1# exit 
    Current State : Standby 
Router1slot2# showstats 
    Active stats    : 59 
    Active stats1   : 56 
Router1slot2# exit 

我想什麼是從輸出獲取一些值並將它們顯示在列,被分隔「」:

Router1slot1,Active,31,47 
Router1slot2,Standby,59,56 

我更近了一步我想要使用:

cat switch.log | awk '/# show/ {print substr($1,1)} /State :/ {print substr($4,1)} /:/{print substr($5,1)}' >> awk.csv 

Output: 

Active 

Router1slot1# 
31 
47 
Standby 

Router1slot2# 
59 
56 

從這裏我嘗試了不同的選項將行轉換爲列,但它似乎並沒有工作。輸出類似於:

56uter1slot2#59 

是否有任何(更有效)的方式來獲取所需的格式?

+0

嗨,下列任何答案對您有幫助嗎?如果他們確實如此,除了回答之外,通過勾選正確的符號來接受/提出答案。如果他們沒有幫助,請解釋預期的情況。 –

回答

2

利用給定的數據下一個應該工作,假設不會有任何空行

輸入

$ cat file 
Current State : Active 
Router1slot1# showstats 
    Active stats    : 31 
    Active stats1   : 47 
Router1slot1# exit 
    Current State : Standby 
Router1slot2# showstats 
    Active stats    : 59 
    Active stats1   : 56 
Router1slot2# exit 

輸出

$ awk -F'[#:]' -v OFS=, '/exit/{print r,s; r=s=""; next}/showstats/{r=$1;next}{s=(s?s OFS:"")$2}' file 
Router1slot1, Active, 31, 47 
Router1slot2, Standby, 59, 56 

說明

awk -F'[#:]' -v OFS=, '    # call awk set and input and ouptut field sep 
    /exit/{       # if exit word found in record 
      print r,s;    # print variable r, and s 
      r=s="";     # set variable r and s to null 
      next     # stop processing go to next line 
    } 
    /showstats/{     # if showstats found 
      r=$1;     # copy first column to variable r 
      next     # stop processing go to next line 
    } 
    { 
     s=(s?s OFS:"")$2    # variable s contains 2nd field of each line 
            # (which is not skipped above using next), 
            # if s was set before then concatenate 
            # s with current record 2nd field, 
            # where separator being OFS between 
            # them (OFS=output field separator) 
    }' file 
+0

這非常有用,謝謝!有沒有辦法讓它工作,如果我會在每個「Router1slotx#exit」之後有一個空行? –

+0

@dxxbstu:只要將'{s ='修改爲'NF {s =' –

0

試試這個 -

awk -F':' '{ORS=(NR%5==0?RS:FS)}1' f|awk -F'[:# ]+' '{print $5,$4,$9,$12}' OFS=, 
Router1slot1,Active,31,47 
Router1slot2,Standby,59,56 
1
awk ' BEGIN{RS="# exit";OFS=","}{$1=$1} length($0){gsub(/#/,"",$5);print $5,$4,$10,$14}' input 
Router1slot1,Active,31,47 
Router1slot2,Standby,59,56 

這將劃分文本到由# exit分開記錄,然後打印選定的列按規定。 gsub是從槽號字段中刪除井號。 length($0)是從結果中刪除空行。

相關問題