Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWK Beginner Bar Graph/Histogram

I've been assigned this prompt as legitimately my first real awk program and I'm not even sure where to start. Any help to get started would be greatly appreciated.

Write an awk program called hist.awk that reads a file of numbers and prints a histogram of occurrences. For the input shown below:

1
4
5
0
2
4
6
8
1
3
2
4
6
7
2
3
3
4
4

The output will be:

0:        1 ***
1:        2 ******
2:        3 ********
3:        3 ********
4:        5 **************
5:        1 ***
6:        2 ******
7:        1 ***
8:        1 ***

The first column contains the numbers from the file. The second contains the number of times that number occurred. The graph shows the percentage of the total, scaled to 50, so 50 asterisks indicates 100%, 25 asterisks indicates 50%, and so on.

like image 684
Nick Soares Avatar asked Feb 15 '26 23:02

Nick Soares


1 Answers

Could you please try following awk and let me know if this helps you(though I am still not sure about your * printing in output).

awk 'function astrick_printing(var){;num=val=count="";count=((var*100)/50);while(++num<=count){val=val "*"};return val;} {a[$0]++} END{for(i in a){print i,a[i],astrick_printing(a[i])}}'  Input_file | sort

Adding non one liner form of above solution too now:

awk '
function astrick_printing(var){
  num=val=count="";
  count=((var*100)/50);
  while(++num<=count){
    val=val "*"};
  return val
}
{
  a[$0]++
}
END{
  for(i in a){
    print i,a[i],astrick_printing(a[i])}
}
'  Input_file | sort

Output will be as follows:

0 1 **
1 2 ****
2 3 ******
3 3 ******
4 5 **********
5 1 **
6 2 ****
7 1 **
8 1 **
like image 80
RavinderSingh13 Avatar answered Feb 19 '26 19:02

RavinderSingh13



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!