目前我使用:
#!/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
你的意思是你想要为每个非发生长度打印一个零,直到最大长度?如果是这样:
$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
示例运行:
$printf 'x\nfoo\n' | ./test.sh 0 0 1 1 2 0 3 1