Subtraction while reading a variable value

Hi Guru's

i have a file which contains data as below(file.txt) and an inital value 8725

 403
 352
 462
 359
 317
 347
 414
 285
 308
 350
 300
 305
 381
 319
 373
 358
 329
 318
 360
 313
 338
 779
 368

how would i read each value in a file and subtract it from the inital value?

i tried using below format, But it failed with syntax error.

state3=8725
while read $ct 
do
TOTAL=`expr $state3 - $ct`
echo $TOTAL
done < file.txt

Please advice how to achieve this?

can u tell us what error u r getting??

here's the error

expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error
expr: syntax error

Also use code tags when posting error logs, example data, code snippets, thanks. Indention of code can also be useful.

Remove the $ :

while read ct 
1 Like

change the below line and execute...

while read ct

its not $ct

1 Like

Opps!! Thanks guys :slight_smile: :b: works now

---------- Post updated at 09:01 PM ---------- Previous update was at 08:06 PM ----------

One more update to it.

the output should be in format

$state3 - $(addition of all number's in file.txt)

the current code captures one value of file.txt and subtracts.

# perl -le '$x=0;$state3=8725;open I,"<input";while(<I>){$x+=$_} print $state3-$x;close I'
287

Thanks Bala any way via Shell?

# s=0;while read x;do s=$(($s + $x));done < file.txt;echo $((8725 - $s))
287
1 Like

in ur code replace as

state3=`expr $state3 - $ct`
1 Like

Thanks a ton Bala and Siva..appreciate your help on this :slight_smile:

An awk solution...

awk '{b+=$1}END{print a-b}' a=8725 input_file

--ahamed

1 Like