Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This is a bc output, e.g.:

Input:

echo "scale=10; BLA-BLA-HERE-NOT-IMPORTANT" | bc

Output:

.3708446283953709207058828124021300754352578903651372655882743141882\
77124645102027246581819139527644919407424570060822470537797066353573\
96635.8038454068 days

Two Questions:

  • can the output be rounded to something like "0.3708..."?
  • can I remove the "\n"-s from the end?

I can't find any max width option in bc.

share|improve this question

4 Answers 4

up vote 2 down vote accepted

You can try something like this code:

echo "scale = 4;  3.5678/3" | bc | tr '\n' ' '

Setting scale for bc is supposed to do the rounding job. You can substitute the division part with your desired command. The output of bc is again piped to tr, which converts the newline (\n) to white space. For the above command I get the following output:

1.1892 user@localhost:~/codes$
share|improve this answer

In GNU bc there is a print statement which not outputs newline:

bash-4.2$ bc <<< 'scale = 4; print 3.5678/3'
1.1892bash-4.2$ 

Also a bare string is output as is:

bash-4.2$ bc <<< 'scale = 4; print 3.5678/3; " days||"'
1.1892 days||bash-4.2$

(The two pipes included just to visually emphasize the end of output. If this was not an example for the bare string, it could be used as print's second parameter.)

share|improve this answer
OUT=$(echo "($BIGNUMBER+2^256)^2" | bc) ; echo $OUT
13407807929942597099574024998205846127479365820592393377723561443721\ 92709106743752503533416270312851677498564874137742504389270445080969\ 1039258113376102500

OUT=$(echo ${OUT//\\/ } | sed s#\ ##g)
echo $OUT
13407807929942597099574024998205846127479365820592393377723561443721927091067437525035334162703128516774985648741377425043892704450809691039258113376102500
share|improve this answer
1  
Wow, that's a complicated way (and originally wrong, too) of writing OUT=${OUT//$'\\\n'/}. –  Gilles Feb 16 '12 at 7:06

There is an environment variable you can set called BC_LINE_LENGTH that will either disable the backslash + newline feature or will extend it. Newer versions allow you to disable it with a value of 0 like this:

BC_LINE_LENGTH=0 bc <<<"2^4096"

Older versions don't have the "0 turn off" feature and require you to set the value to a large enough value so that it doesn't affect you:

BC_LINE_LENGTH=10000 bc <<<"2^4096"

Seems like this would be a good environment variable to set in your shell if you use bc a lot and don't like the line wrapping. If you're using BASH, just place this in your .bashrc:

export BC_LINE_LENGTH=0
share|improve this answer

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.