Bash uses sparse arrays by default. For example. there could be holes in the array. You can avoid them by initializing (filling) the array in advance. Of course, you need to evaluate the maximum index. e.g. add to top
histogram=( $(printf "%0.s0\n" {1..10}) )
after you run how
printf "%s\n" 1 123 123 123456 | bash the_script
You'll get:
0 0 1 1 2 0 3 2 4 0 5 0 6 1 7 0 8 0 9 0
or , if you do not want to initialize in advance, you need to check the existence of this member and execute a loop for each
while read line do ((histogram[${#line}]++)) done < "${1:-/dev/stdin}" max=$(printf "%s\n" "${!histogram[@]}" | sort -nr | head -1) for ((length=0; length<=max; length++ )) { val=${histogram[$length]:-0} printf "%-1s %s\n" "${length}" "$val" }
eg. for the above printf "%s\n" 1 123 123 123456 | bash the_script printf "%s\n" 1 123 123 123456 | bash the_script
0 0 1 1 2 0 3 2 4 0 5 0 6 1
jm666
source share