Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Histogram with bash

Tags:

bash

Currently I use:

#!/bin/bash
while read line
do
    ((histogram[${#line}]++))   
done < "${1:-/dev/stdin}"

for length in "${!histogram[@]}"; do
    printf "%-1s %s\n" "${length}" "${histogram[$length]}"
done

to generate a histogram output. But if there are no lines of length, the output automatically omit them. Is there any ways to let the function do not omit those lines? Any ideas?

like image 987
Charles Smith Avatar asked Apr 15 '17 07:04

Charles Smith


1 Answers

Do you mean that you want to print a zero for every non-occurring length up to the max length? If so:

$ cat test.sh 
#!/bin/bash
while read line
do
    ((histogram[${#line}]++))
done < "${1:-/dev/stdin}"

max=0
for length in "${!histogram[@]}"
do
    if [ $length -gt $max ]
    then
        max=$length
    fi
done

for length in $(seq 0 $max)
do
    printf "%-1s %s\n" "${length}" "${histogram[$length]-0}"
done

Example run:

$ printf 'x\nfoo\n' | ./test.sh
0 0
1 1
2 0
3 1
like image 177
l0b0 Avatar answered Sep 23 '22 06:09

l0b0