grep或awk切2条不同的线

时间:2015-05-06 20:14:20

标签: linux awk sed grep

我在下面有一个名为 monitor.log

的报告文件
switch#sh mac address-table int g1/0/1
          Mac Address Table
-------------------------------------------

Vlan    Mac Address       Type        Ports
----    -----------       --------    -----
 110    000f.ffff.ffff    STATIC      drop
Total Mac Addresses for this criterion: 1
switch#sh mac address-table int g1/0/4
          Mac Address Table
-------------------------------------------

Vlan    Mac Address       Type        Ports
----    -----------       --------    -----
 110    000f.ffff.ffff    STATIC      drop
Total Mac Addresses for this criterion: 1
switch#sh mac address-table int g1/0/3
          Mac Address Table
-------------------------------------------

Vlan    Mac Address       Type        Ports
----    -----------       --------    -----
 110    000f.ffff.ffff    STATIC      drop
Total Mac Addresses for this criterion: 1

我想要一个使用grep,awk或sed的命令只显示那些字段并保存到文件中,即:

int g1/0/1 drop 
int g1/0/2 drop
int g1/0/3 drop

3 个答案:

答案 0 :(得分:1)

$ awk -v RS='switch#sh' '$3 {print $3,$4,$21}' monitor.log
int g1/0/1 drop
int g1/0/4 drop
int g1/0/3 drop

将报告限制为drop条目:

awk -v RS='switch#sh' '$21=="drop" {print $3,$4,$21}' monitor.log

处理多行的表

假设输入文件如下:

$ cat monitor.log2
switch#sh mac address-table int g1/0/1
Mac Address Table
-------------------------------------------

Vlan Mac Address Type Ports
---- ----------- -------- -----
110 000f.ffff.ffff STATIC drop
200 000f.ffff.ffff STATIC drop
Total Mac Addresses for this criterion: 1 
switch#sh mac address-table int g1/0/2
          Mac Address Table

然后使用:

$ awk '/switch#sh/{a=$4" "$5} /----/,/Total Mac Addresses/ {if ($4=="drop")print a,$4}' monitor.log2
int g1/0/1 drop
int g1/0/1 drop

答案 1 :(得分:0)

使用GNU grep,paste,bash

paste -d" " <(grep -oP '(?<=mac address-table ).+' monitor.log) \
            <(grep -oP '\d+\s+[[:xdigit:].]+\s+\w+\s+\K.+' monitor.log)

使用GNU sed,粘贴

sed -rn '
    s/.*mac address-table //p
    s/\s+[[:digit:]]+\s+[[:xdigit:].]+\s+[[:alpha:]]+\s+//p
' monitor.log | paste -d" " - -

答案 2 :(得分:0)

sed -n '/^switch#sh/,/^Total/ {
   /^switch#sh mac address-table / {s///;h;}
   /[[:space:]]*drop$/ {g;s/$/ drop/p;}
   }' YourFile
  • 如果订单很重要,则管道排序更容易
  • 假设仅在 drop 出现在交换条目
  • 的部分中时才打印