Brian Brian - 3 months ago 14
Linux Question

Best way to divide in bash using pipes?

I'm just looking for an easy way to divide a number (or provide other math functions). Let's say I have the following command:

find . -name '*.mp4' | wc -l


How can I take the result of wc -l and divide it by 3?

The examples I've seen don't deal with re-directed out/in

Thanks

Answer

Using bc:

$ bc -l <<< "scale=2;$(find . -name '*.mp4' | wc -l)/3"
2.33

In contrast, the bash shell only performs integer arithmetic.

Awk is also very powerful:

$ find . -name '*.mp4' | wc -l | awk '{print $1/3}'
2.33333

You don't even need wc if using awk:

$ find . -name '*.mp4' | awk 'END {print NR/3}'
2.33333
Comments