Brian Brian - 1 year ago 73
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


Answer Source

Using bc:

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

In contrast, the bash shell only performs integer arithmetic.

Awk is also very powerful:

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

You don't even need wc if using awk:

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