Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
Hi,
I have a file with 3 lines as follow.Ex:
Trading amt=10
Pending amt=3
Available amt=4
I want to subtract the total of pending and available amts from trading amt and display all 4 rows (4th row being Others=3)into a new file. How can I do the same in Shell script?

Any number of methods will solve this problem. Ghostdog will probably give you an awk script and Fishmonger will submit a perl script.
As long as you are doing integer arithmetic. I choose to use the (mostly) Korn shell itself. Given the structure of your data, get rid of the word 'amt' and the space, and you can actually create the variables, Trading, Pending, and Available, using the unix eval command:
#!/bin/ksh newfile=newdatafile.txt rm -f $newfile while read line do # get rid of the 'amt' and spaces. var=$(echo "$line"|sed -e 's/amt//g' -e 's/ //g') eval echo \""\${$var}"\" > /dev/null # echo "trading is: $Trading" echo "$line" >> $newfile done < datafile.txt others=$(($Trading-$(($Pending+$Available)) )) echo "Others=$others" >> $newfile

I would do like this,
$ Trading_amt=10; Pending_amt=3; Available_amt=4; other=`expr $Pending_amt + $Available_amt`; others=`expr $Trading_amt - $other`; echo $Trading_amt; echo $Pending_amt; echo $Available_amt; echo $others.
This is actually a one -ler i tried on the command line.

![]() |
![]() |
![]() |
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |