AWK: How to count number of entries for a month
I hope all of you are aware with AWK. This example will help you to understand AWK practically.
Sample Data:
10-Jul-10 23-Jul-10 : 31-Jul-10 1-Aug-10 : 4-Aug-10 5-Aug-10
awk 'BEGIN{
FS="-";OFS=","
}
{
$1="";
print substr($0,2,length($0))
}'
dates.txt
| sort |
awk 'BEGIN{
getline;
lastline=$0;
count=1;
}
{
if(lastline==$0)
{
count+=1;
}
else{
print lastline": "count;
lastline=$0;
count=1;
}
}
END{
print lastline": "count;
}'
Output:
Aug,10: 5
Jul,10: 22
Explanation:
We can break above commands in 3 parts. First part removes the date. And gives filtered out put like;
Jul,10 Jul,10 Jul,10 : Jul,10 Aug,10 : Aug,10 Aug,10
There may be a change that text file or input data have dates in any order. So the sort command just sorts the output given by first command. And provides support to third command. 3rd command is again a AWK command. And it searches for continuity of a pattern. Once pattern changes it prints the count.
To understand AWK examplesyou must read basic structure of AWK command.
