如何列印匹配/不匹配模式的計數以及列印按行分隔的多個模式。
輸入範例(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
==========================================
到目前為止我已經嘗試過:
- 取得行數:
egrep -o '8888|3333|5555' test.log | sort| uniq -c
輸出:
4 3333
2 8888
但它不會列印0 5555
來指示檔案 test.log 中五個出現次數為零
期望的輸出:
4 3333
2 8888
0 5555
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];
}
}