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.
find . -name '*.mp4' | wc -l | xargs -I{} expr {} / 2
Best used if you have multiple outputs you'd like to pipe through
xargs
. Use{}
as a placeholder for the expression term.Edit 2018-02-22: Adding
shell connector
There is more than 1 way:
Depending on precision required and number of calcul to be done! See
shell connector
further!Using
bc
(binary calculator)or
or using bash, result in integer only:
Using bash interger builtin math processor
Pure bash
With recent 64bits bash, you could even use @glennjackman's ideas of using
globstar
, but computing pseudo floating could be done by:There is no fork and
$res
contain a two digit rounded floating value.Nota: Care about symlinks when using
globstar
and**
!Introducing
shell connector
If you plan to do a lot of calculs, require high precision and use bash, you could use long running
bc
sub process:then now:
This subprocess stay open and useable:
Computing
$PI
:To terminate sub process:
Little demo, about The best way to divide in bash using pipes!
Computing range
{1..157} / 42
( I will let you google foranswer to the ultimate question of life, the universe, and everything
;)... and print 13 result by lines in order to reduce output:
By regular way
By using long running
bc
sub process:Let's see without:
Wow! Ten seconds on my raspberry-pi!!
Then with:
Less than one second!!
Hopefully, results are same, but execution time is very different!
My
shell connector
I've published a connector function: Connector-bash on GitHub.com and shell_connector.sh on my own site.
Using
bc
:In contrast, the bash shell only performs integer arithmetic.
Awk is also very powerful:
You don't even need
wc
if usingawk
:Depending on your bash version, you don't even need find for this simple task:
This method will correctly handle the bizarre edgecase of filenames containing newlines.