0

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

#!/bin/bash
#n1=$(wc -l < input.txt) #input.txt is a text file with 10000 lines
n1=10000
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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Kay
  • 1,957
  • 2
  • 24
  • 46

2 Answers2

3

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)
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
1

Rather than start a new process to count the records in the file and then passing that to awk, I would suggest you let awk count the records itself which it does anyway in the variable NR. So, your entire script would become:

percentage=$(awk 'END{print NR*0.05/100}' input.txt)
Mark Setchell
  • 191,897
  • 31
  • 273
  • 432