0

So, suppose I have the following, where I create 2 variables in a shell (bash) script that are the output of various commands:

# total number of records in file
tot=$(wc -l < /usr/local/test.dat)
echo "total records is: ${tot}"

# number of those records that contain the word wumpus
den=$(grep -r "wumpus" /usr/local/test.dat | wc -l)
echo "total lines containing wumpus: ${den}" 

Works fine. But, what I want to do next is calculate the proportion of lines in the file containing wumpus. In other words, den/tot, and echo that. I've tried most permutations of things like the following, but no luck.

# calculate proportion
prop=$(${den}/${tot})
echo ${prop}

Am I correct in concluding that 'doing math' on a bash variable that is the output of a command is somehow different than doing math with explicitly declared bash variables? For example, the following works fine

a=2
b=3
echo $(($a+$b))
  • 2
    Your example that works fine does `$(( stuff ))`. The one that doesn't does `$( stuff )`. – Mat Mar 31 '23 at 13:09
  • Doesn't work for me. echo $(( ${den}/${tot} )) prints a 0. Tried various permutations (e.g., $(( ${den}/${tot} )), $(( $den/$tot)), ...). Nada... – Johnny Canuck Mar 31 '23 at 13:11
  • Bash only does integer arithmetic, so that result is "correct" – Mat Mar 31 '23 at 13:13
  • bash supports only integer arithmetic. You must resort to an external utility (`bc`, for instance): `bc -l <<< "$den/$tot"` – M. Nejat Aydin Mar 31 '23 at 13:13
  • https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-arithmetic-in-bash – Mat Mar 31 '23 at 13:14
  • bc -l did the trick. Thanks. I suppose I should have realized bash does only integer arithmetic. Many thanks. – Johnny Canuck Mar 31 '23 at 13:16
  • 1
    As an aside, this `awk` one-liner would do the job at once: `awk '/wumpus/{++n} END{print n/NR}' /usr/local/test.dat` (you'll get a "division by zero" error if the file is empty) – M. Nejat Aydin Mar 31 '23 at 13:27

0 Answers0