Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: how to perform arithmetic on numbers in a pipe

I am getting a stream of numbers in a pipe, and would like to perform some operations before passing them on to the next section, but I'm a little lost about how I would go about it without breaking the pipe.

for example

> echo "1 2 3 4 5" | some command | cat 
1 4 9 16 25
>

Would you have any ideas on how to make something like this work? The actual operation I want to perform is simply adding one to every number.

like image 254
brice Avatar asked Jul 17 '10 16:07

brice


People also ask

How do you float arithmetic in bash?

While you can't use floating point division in Bash you can use fixed point division. All that you need to do is multiply your integers by a power of 10 and then divide off the integer part and use a modulo operation to get the fractional part.

Which command is used to perform arithmetic?

With the print command, the result of an arithmetic operation can be used and printed in the command window.


1 Answers

echo 1 2 3 4 5|{
  read line; 
  for i in $line;
  do
    echo -n "$((i * i)) "; 
  done; 
  echo
}

The {} creates a grouping. You could instead create a script for that.

like image 191
Matthew Flaschen Avatar answered Oct 01 '22 14:10

Matthew Flaschen