0

how to print the count of matched /unmatched patterns and print multiple patterns separated by line.

Input example (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

Desired output :

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
==========================================

what i have tried so far :

  1. to get the number of lines: egrep -o '8888|3333|5555' test.log | sort| uniq -c

output:

4 3333
2 8888

but it's not printing 0 5555 to indicate zero occurrence of five in file test.log

desired output:

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

this sort output in alphabetic order and not according to the output i expect as shown below :

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 Answer 1

2

The program you're looking that can easily do what you want is called awk. :-)

It can do programmed actions on matched RE patterns.

Untested, simplified, rote, example awk program that should work with your example input and specified patterns:

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];
    }
}
2
  • Thank you so much for sharing this wonderful program .millions of thanks . i know basics of awk but im a fresher kindly explain how these syntax work in awk /8888/ { eightln[eights] = $0; eights++; } for (i = 0; i < fives; i++) { print fiveln[i]; }
    – star
    Commented May 22, 2016 at 20:05
  • I'm sure a simple Google search can lead you to many documents that describe AWK syntax in varying degrees of detail. However I would recommend starting at the Wikipedia article: en.wikipedia.org/wiki/AWK Commented May 22, 2016 at 22:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .