AWK - 匹配多个模式并在一行中打印结果

时间:2017-03-23 00:38:19

标签: awk

使用我有限的脚本知识..我已经整理了一个expect脚本来在特定设备上运行一些命令。输出在下面,并从所有设备保存到文件中(我刚刚列出了2个设备作为示例)。

  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

有没有(更有效)的方式来获得所需的格式?

3 个答案:

答案 0 :(得分:3)

使用下面的给定数据,假设不存在空行

,则应该有效

<强>输入

$ 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 

答案 1 :(得分: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)将清除结果中的空白行。

答案 2 :(得分: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