7

I have the following example in GNU v. 1.06 (I cannot identify a limit pertaining to line length):

v=$(bc -l <<<"scale=100;4*a(1)"); echo $v

which returns:

3.141592653589793238462643383279502884197169399375105820974944592307\ 
8164062862089986280348253421170676

Is it possible to remove the backslash and carriage return in this function's output, or am I looking for something that doesn't exist?

2 Answers2

9

At least in GNU bc, you can set environment variable BC_LINE_LENGTH to a zero value e.g.

BC_LINE_LENGTH=0 bc -l <<<"scale=100;4*a(1)"

From man bc:

BC_LINE_LENGTH
       This should be an integer specifying the number of characters in
       an  output  line  for  numbers.  This includes the backslash and
       newline characters for long numbers.  As an extension, the value
       of  zero  disables  the  multi-line feature.  Any other value of
       this variable that is less than 3 sets the line length to 70.
steeldriver
  • 81,074
2

With the GNU implementation of bc, starting with version 1.07 you can use BC_LINE_LENGTH=0 (DC_LINE_LENGTH=0 for GNU dc) to disable line wrapping altogether as already mentioned. With older versions of GNU bc, you can use BC_LINE_LENGTH=9999 (or any value greater than the maximum size of the number you're expecting to see).

BC_LINE_LENGTH=9999 bc -l <<< 'scale=100;4*a(1)'

For other implementations, you could instead pipe to:

perl -pe 's/\\\n\z//'

or

sed -e :1 -e '/\\$/{N;s/\\\n//;b1' -e '}'

or

awk '{if (sub(/\\$/, "")) printf "%s", $0; else print}'

or (golf version):

awk '{ORS=sub(/\\$/,"")?"":RS};1'

Beware though that on some systems, text utilities don't support lines larger than some maximum (see getconf LINE_MAX which could be as low as 1024 bytes).

  • The sed version could be written as sed -e ':1;/\\$/{N;s/\\\n//;b1}' – Hynek -Pichi- Vychodil Mar 16 '21 at 12:26
  • @Hynek-Pichi-Vychodil, no that's not standard sed syntax. You can't have another command after the : or b command (in the original sed implementation, ; is allowed in a label name) and you need a ; before }. Yours would only work in the GNU implementation of sed. – Stéphane Chazelas Mar 16 '21 at 15:31