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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With