What can i do with a loop, read expr and echo command to produce a new file like below:
12345678:12
23456789:20
and also when we adding fewer than 3 value with expr, we need to change any null value for variable to 0 so expr gets a valid argument. how can i change it?
So how can i produce a new file with the format above? Using Bourne Shel script.
Thank you for your helping!!
One way in "ksh" (you don't state which shell). Note there are Posix ways of doing arithmetic in shell without using "expr" and there are ways of reading a file without using "cat". I hope I have understood the sums required because I make 7+9+3=19 .
Your input consists of records/line where each field is separated from the other by space.
You need to sum up ALL the fields start from the SECOND field of each record/line and then print the FIRST field and the SUM.
nawk '
# a set of actions to be taken for every record/line
{
# initialize the "sum" to zero for current record/line
sum=0
# iterate through the fields starting at (i=2) till the maximum number of field (NF)
# of the current record/line. For every iteration the the value of the currently
# iterated field ($i) to the sum (sum+=$i)
for(i=2;i<=NF;i++)
sum+=$i
# once the iteration loop is complete, print FIRST field and the "sum".
# The "," in the "print" statement get evaluated to the value of the OFS
# OFS - OutputFieldSeparator
print $1,sum
}' OFS=: myFile
# Assign ":" to OFS and pass the input file "myFile" to be be parsed by the script.
Finding an old Bourne Shell to try was fun.
There are better ways to deal with null parameters than the way I show. It is the way suggested in original Bourne manuals.
Ignore 1st line unless that happens to be where you find Bourne shell. Unlike "ksh" the Bourne shell did not put zero in a blank numeric parameter.
#!/usr/old/bin/sh
A2=0
A3=0
A4=0
TOTAL=0
cat Marks | awk '{print $1,$2,$3,$4}'|while read A1 A2 A3 A4
do
if [ "${A2}""X" = "X" ]
then
A2=0
fi
if [ "${A3}""X" = "X" ]
then
A3=0
fi
if [ "${A4}""X" = "X" ]
then
A4=0
fi
#
TOTAL=0
TOTAL=`expr ${TOTAL} + ${A2}`
TOTAL=`expr ${TOTAL} + ${A3}`
TOTAL=`expr ${TOTAL} + ${A4}`
echo "${A1}:${TOTAL}"
done[/CODE
The "awk" statement is completely surplus because the fields in the records are already delimited with a space character. The "cat" can be replaced with inward redirect ... but I have chosen not to.
#!/usr/old/bin/sh
A2=0
A3=0
A4=0
TOTAL=0
cat Marks |while read A1 A2 A3 A4
do
if [ "${A2}""X" = "X" ]
then
A2=0
fi
if [ "${A3}""X" = "X" ]
then
A3=0
fi
if [ "${A4}""X" = "X" ]
then
A4=0
fi
#
TOTAL=0
TOTAL=`expr ${TOTAL} + ${A2}`
TOTAL=`expr ${TOTAL} + ${A3}`
TOTAL=`expr ${TOTAL} + ${A4}`
echo "${A1}:${TOTAL}"
done