Kayan Kayan - 1 year ago 78
Bash Question

how to calculate percentage in shell

I would like to calculate percentage in shell. But I can't do it. My script is

#n1=$(wc -l < input.txt) #input.txt is a text file with 10000 lines
n2=$(awk '{printf "%.2f", $n1*0.05/100}')
echo 0.05% of $n1 is $n2

It is neither showing any value nor terminating when executing this script.

Answer Source

awk will give you an n1 illegal field name if you do that, as it's inside single quotes. Also, to avoid awk keep reading stdin you should pass /dev/null as file. Then:

n2=$(awk -v n1="$n1" 'BEGIN {printf "%.2f", n1*0.05/100}' /dev/null)