LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   arithmetic in bash (https://www.linuxquestions.org/questions/linux-newbie-8/arithmetic-in-bash-876531/)

xeon123 04-22-2011 11:07 AM

arithmetic in bash
 
Hi,

I've a txt file that contains values in 2 columns:
Code:

#field1  field2
324        2343
232        13434
213        453
54        231

I would like to apply the equation 1/(1-(field1/field2)) in bash. How can I do that?

kurumi 04-22-2011 11:11 AM

If this is not homework, try a different tool than bash.
Code:

$ ruby -ane 'puts $F[0].to_f/$F[1].to_f' file
you can use also awk,Perl, Python etc that can support decimals

xeon123 04-22-2011 11:15 AM

This is not homework. I prefer in bash.

Here's the command that I use and it won't work.
expr 1/(`cat tmp.txt | awk '{ print $1/$2 }'`)

grail 04-22-2011 11:59 AM

Well you just said in bash but are using awk?? As kurumi said, awk can do it on its own.
Code:

awk 'NR>1{print 1/(1 - $1/$2)}' file
Bash does not do fractions so you will at least need to use bc.

arizonagroovejet 04-22-2011 01:12 PM

Code:

answer=$((1/(1-(field1/field2))))
answer will be rounded to the nearest integer.

http://tldp.org/LDP/abs/html/arithexp.html

grail 04-23-2011 01:18 AM

@arizonagroovejet - I do not see how your solution is of any use? All answers will be 1 as the fraction portion will always equate to 0 so it is just 1/1.

arizonagroovejet 04-23-2011 04:12 AM

Quote:

Originally Posted by grail (Post 4333337)
All answers will be 1 as the fraction portion will always equate to 0 so it is just 1/1.

Yeah... good point. What I posted works and meets the OP's original stated requirement/desire of doing it in bash but you're right, it isn't of any practical use in this case given the numbers being used.

xeon123 04-23-2011 09:07 AM

Hi grail,

can you explain me what are you saying please? How the fraction part is always 0?

grail 04-23-2011 09:24 AM

All of the numbers in your file when column 1 is divided by column 2 will end up as a fraction less than 1. Bash does not actually round numbers to the nearest integer,
it actually truncates the decimal portion so all of your values will equate to 0.

Hope that helps.

xeon123 04-23-2011 09:39 AM

Thanks, now I get it.


All times are GMT -5. The time now is 05:41 AM.