Remove carriage return from the variable

Hi,

I try to handle very large numbers with a bash script. I run ssh command in a remote server and store the output in a local variable. But this output contains a return carriage at the end. So I try to remove it by tr But I can't figure out the right notation with printf. So my problem is:

 
var1=$( some command )

echo $var1
2.80985e+09
 
var2=`expr $var1 + 10000000`
expr: non-integer argument

printf "%f\n" $var1
2809850000.000000

printf "%s\n" $var1
2.80985e+09


If I use tr -dc '[:digit:]' with this printf output, it will remove all non character not only return carriage at the end.

So for first notation it will give me a number like 2809850000000000 and for second 28098509 and both incorrect. I need a display like 2809850000 so tr could only remove return carriage. So which parameter of printf would produce this notation? (w/o exponential nor decimal notation)

Thanks

You could use awk also

$ a="2.80985e+09\r\r\n"
$ echo $a
2.80985e+09\r\r\n

$ b=$(awk -v var=$a 'BEGIN{print var+10000000}')
$ echo $b
2819850000

Actually I have a lot of variables, 5,6 sometimes even 10. So I should perform arithmetic operations with all of them.

So I need something like (after your example)

a=20000000000000000000^m
b=300000000000000000000^m
c=40000000000000000000^m
d=250000000000000^m

e=$( awk -v var1=$a var2=$b var3=$c var4=$d 'BEGIN{print var1 * var2 / var3 + var4}' ) 

But this example above didn't work. Do you have any suggestion for this?

I didn't see calculation part -v is missing

e=$( awk -v var1=$a -v var2=$b -v var3=$c  -v var4=$d 'BEGIN{print var1 * var2 / var3 + var4}' )
1 Like

Oh I see. I need a separate -v for each variable. It worked like that. Thanks buddy. This saved my life :slight_smile: :b::b:

Yes, it's for defining variable

from man page of awk

-v var=val
       --assign var=val
              Assign the value val to the variable var, before execution of the program begins.  Such variable values are  available  to  the
              BEGIN block of an AWK program.

Please be careful - that trick with awk works because when converting a field to a numerical value, awk will start at the beginning of the field and scan until an unconvertible char is encountered - which is "\" "r" in post#2. Yes - it's not <CR> but two normal chars.

 a="2.80985e+09\r\r\n"
echo $a xxx
2.80985e+09\r\r\n xxx
a="2.80985e+09"$'\r'
echo $a xxx
 xxx985e+09

The second assignment really has a <CR> char in it, making echo overprint the first chars.
To remove the <CR>, you can try this bashism (pattern substitution expansion):

echo ${a/$'\r'} xxx
2.80985e+09 xxx

or e.g.

echo $a  |hd
00000000  32 2e 38 30 39 38 35 65  2b 30 39 0d 0a
echo $a |tr -d '\r' |hd
00000000  32 2e 38 30 39 38 35 65  2b 30 39 0a