Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose two numbers are stored in two different files. a.txt and b.txt. Each number say large enough(more than 30 digit) not to be supported by data types. So how to add them in bash shell.?

share|improve this question
    
Personally I would use python or similar in that case. – phk 17 hours ago
    
Sure you don't want to use sed for addition instead? – Jeff Schaller 15 hours ago

Assuming they are decimal numbers, You could do:

paste -d + a.txt b.txt | bc

Beware that bc line-wraps very long numbers (more than 68 or 69 digits depending on the implementation). With GNU bc, you can disable it by setting the BC_LINE_LENGTH environment variable to 0, like with:

paste -d + a.txt b.txt | BC_LINE_LENGTH=0 bc
share|improve this answer

The trick is to not use bash to perform the addition.

First, read each number into a separate variable. This assumes that the files contain only a number and no other information.

a="$(<a.txt)"
b="$(<b.txt)"

Then use the bc calculator to get the result:

bc <<<"$a + $b"

bc is a "arbitrary-precision arithmetic language and calculator".

To store the result in a variable c:

c="$( bc <<<"$a + $b" )"

If the <<< syntax feels weird (it's called a "here-string" and is an extension to the POSIX shell syntax supported by bash and a few other shells), you may instead use printf to send the addition to bc:

printf '%s + %s\n' "$a" "$b" | bc

And storing the result in c again:

c="$( printf '%s + %s\n' "$a" "$b" | bc )"
share|improve this answer
1  
Alternatively, you could do read a < a.txt. That would also take care of stripping leading and trailing blanks if any (assuming $IFS has not been modified). – Stéphane Chazelas 15 hours ago
    
Why do the quotes inside the quotes not need to be escaped for the here-string inside the process substitution? – Bryce Guinta 9 hours ago
2  
@BryceGuinta Because unlike something like echo "\"hello\"", the thing within the $(...) is not a string passed as an argument to another program, and the shell knows how to deal with the nesting of quotes. This is also why using $(...) rather than backticks is better; you can write $( ... $( ... ) ) without any ambiguity, whereas the same thing using backticks is... awkward. – Kusalananda 8 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.