用于查找带有值的多个单词的unix脚本,然后删除不匹配的行

时间:2013-09-23 14:24:23

标签: regex bash sorting grep

假设我有几个包含此文件的文件:

[srv] $ cat *.file.* | egrep -R -h -A 3 'is up'

interface0/1, is up
0 input errors, 18 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 7299 collisions, 0 interface resets
--
interface0/2, is up
0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 0 collisions, 0 interface resets
--
interface0/5, is up
669 input errors, 192 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 4991 collisions, 0 interface resets
--
.
.
n..
interface0/n, is up
0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 0 collisions, 0 interface resets
--

我想打印出任何具有计数器值的界面>除了接口重置之外,0表示“已启动”。 当我使用grep时,我不会看到该行所属的接口:/

是否可以收集符合我标准的行?

2 个答案:

答案 0 :(得分:0)

如果你想获得包含这些行的文件,你可以直接将参数传递给egrep,而不是使用-H而不是-h

egrep -R -H -A 3 'is up' *.file.*

更新:你可以尝试这个脚本:

#!/usr/bin/env awk -f

/^interface[0-9]+\/[0-9]+, is up/ {
    split($0, a, /[,\/]/)
    if (a[2] > 0) {
        getline b
        getline c
        if (c ~ /0 interface resets$/) {
            printf "%s\n%s\n%s\n--\n", $0, b, c
        }
    }
}

用法:awk -f script.awk *.file.*

示例输出:

interface0/1, is up
0 input errors, 18 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 7299 collisions, 0 interface resets
--
interface0/2, is up
0 input errors, 0 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 0 collisions, 0 interface resets
--
interface0/5, is up
669 input errors, 192 CRC, 0 frame, 0 overrun, 0 ignored
0 output errors, 4991 collisions, 0 interface resets
--

答案 1 :(得分:0)

我认为应该这样做:

sed -n -e '/is up/ {;N;N;/is up.*[1-9].* 0 interface resets/p;}' *.file.*