I run this command in the terminal:grep bla bla blah blah* | echo Blah: $(wc -l) / $(ls | wc -l) * 100And I get this output: Blah: 44 / 89 * 100What I expect to see: 49.4Is there a way to obtain the desired output using just the bash commands? I don't prefer scripts I am planning to pipe the output.
How to calculate values in a shell script?
bash;arithmetic;bc
Your code says to print a string. It doesn't say anywhere that this string is in fact an arithmetic expression that you want evaluated. So you can't reasonably expect your expression to be evaluated.Your code is suboptimal. $(wc -l) will count the number of matches returned by grep, but there's a simpler way: run grep -c instead. $(ls | wc -l) is an unreliable way of counting the non-dot files in the current directory, because the output of ls isn't reliable; $(set -- *; echo $#) is a reliable way of doing this (assuming there is at least one matching file; if that assumption might not hold, use $(set -- *; if [ -e $1 ]; then echo $#; else echo 0; fi, but note that this will result in a division by zero below which you should treat as an error condition one way or another). So you can write your code this way:matches=$(grep -c bla bla blah blah*)files=$(set -- *; echo $#)echo Blah: $matches / $files * 100or you can inline the computation of the two intermediate values:echo Blah: $(grep -c bla bla blah blah*) / $(set -- *; echo $#) * 100Now, to perform the arithmetic, you can use the shell's built-in arithmetic expansion, but it's limited to integer operations, so the / operator will round down to the nearest integer.echo Blah: $(($matches * 100 / $files))In ksh93, zsh and yash, but not in other shells, you get floating-point arithmetic if there's something in the expression to force floating-point, such as a floating-point constant. This feature is not present in the Bourne shell, ksh88, pdksh, bash, ash.echo Blah: $(($matches * 100.0 / $files))The bc utility performs operations on decimal number with arbitrary precision.echo Blah: $(echo scale=2; $matches * 100 / $files | bc)Another standard utility that can perform floating-point computation (with fewer mathematical functions available) is awk.echo $matches $files | awk '{print Blah:, $1 * 100 / $2}'