如何打印匹配/不匹配模式的计数以及打印按行分隔的多个模式

如何打印匹配/不匹配模式的计数以及打印按行分隔的多个模式

如何打印匹配/不匹配模式的计数以及打印按行分隔的多个模式。

输入示例(test.log):

This 23 line has eight 8888
This 11 line has three 3333
need 12 to separate eight and three 3333
eight 32 is greater than three 8888
three 13 is less than eight 3333
three 14 is printed more than eight 3333

期望的输出:

8888:4
3333:2
5555:0
This 11 line has three 3333
need 12 to separate eight and three 3333
three 13 is less than eight 3333
three 14 is printed more than eight 3333
============================================
This 23 line has eight 8888
eight 32 is greater than three 8888
==========================================

到目前为止我已经尝试过:

  1. 获取行数:egrep -o '8888|3333|5555' test.log | sort| uniq -c

输出:

4 3333
2 8888

但它不会打印0 5555来指示文件 test.log 中五个出现次数为零

期望的输出:

4 3333
2 8888
0 5555
  1. egrep '8888|3333' test.log | sort -V

此输出按字母顺序排序,而不是根据我期望的输出,如下所示:

This 11 line has three 3333
need 12 to separate eight and three 3333
three 13 is less than eight 3333
three 14 is printed more than eight 3333
============================================
This 23 line has eight 8888
eight 32 is greater than three 8888
==========================================

答案1

您正在寻找的可以轻松完成您想要的事情的程序称为awk。 :-)

它可以对匹配的 RE 模式执行编程操作。

未经测试的、简化的、死记硬背的示例awk程序,应该适用于您的示例输入和指定的模式:

BEGIN {
    eights = 0;
    fives = 0;
    threes = 0;
}
/8888/ {
    eightln[eights] = $0;
    eights++;
}
/5555/ {
    fiveln[fives] = $0;
    fives++;
}
/3333/ {
    threeln[threes] = $0;
    threes++;
}
# ... and so on
END {
    printf("%d 8888\n", eights);
    printf("%d 5555\n", fives);
    printf("%d 3333\n", threes);
    for (i = 0; i < eights; i++) {
        print eightln[i];
    }
    print "=========="
    for (i = 0; i < fives; i++) {
        print fiveln[i];
    }
    print "=========="
    for (i = 0; i < threes; i++) {
        print threeln[i];
    }
}

相关内容