Arithmetic with bash

I need to divide the number of white spaces by total number of characters in a file using bash. I am able to get the number of white spaces correctly using:

tr -cd �[:space:]� < afile | wc -c

I am also able to get the total number of characters using:

wc -c afile

How do I divide the first number by second to get the final answer.

My personal first step is always to consult the relevant man pages. bash provides "arithmetic expansion" / "arithmetic evaluation". man bash :

As it provides integer calculations only, we need additional measures as your data will be percentages and never exceed 1. You'll need "command substitution" as well. So - try

echo $(($(tr -cd �[:space:]� < afile | wc -c)00 / $(wc -c < afile)))

The two zero characters are in fact a multiplikation by 100. Be aware that [:space:] includes <TAB>s and <LF>s as well.

bash does integer arithmetics only.

awk '{tot+=length+1; spc+=gsub(/[[:blank:]]/,"")+1} END{print spc/tot}' afile

The +1 takes the newline character into account like the previous wc .