Hi Gurus,
In my file I have an amount field from position 74 to 87, which contains values starting with '+' as well as '-'. I want to add all positive values in a varible called "CREDIT" and all negative values in a variable "DEBIT". I know, we can use grep to identify values with positive and negative signs. But, don't know, how to add them in 2 separate variables in a script. Is there any way to do that on command line? Any help would be much appriciated. Thanks!
In my file Amount field has right justified values like,
+1345778500000
-327800000
+642307000000
-4300000
+2308007
These values look left justified here on the screen, but they are actually right justified in my file.
awk ' {
value=substr($0,74,14)
while (substr(value,1,1) == " " ) {value=substr(value,2)}
if(value>0) { plus+=value}
else {minus+=value}
}
END { print plus, minus} ' filename | read credit debit
try something like that....
.. messed up the right justification...
Thanks jim mcnamara for the reply. It works fine, when values are left justified. But, I have right justified values in the file. So, '+' OR '-' can start at any position from 74 to 87 bytes.
How can we use 'length' function to treat the values as left justified, so the leading spaces can be ignored?
I think, following will solve the problem, where I don't care about position of '+' and '-' signs in the values. I can just check values > 0 and the rest, and according to that sum them in 2 different variables as below:
awk ' {
value=substr($0,74,14)
if(value>0) { plus+=value}
else {minus+=value}
}
END { print plus, minus} ' filename | read credit debit
Following works fine,
#!/bin/ksh
credit_sum=`awk '{ value=substr($0, 74, 14); if(value>0) {credit+=value}} END {print credit}' filename`
debit_sum=`awk '{ value=substr($0, 74, 14); if(value<0) {debit+=value}} END {print debit}' filename`
exit 0;