I would like to compute cumulative values from the below data file and writing them into columns after inserting a serial number.
JavaScript
x
ifile.txt
1 2 3 2 3 1 4 5 1
3 4 5 2 3 4 1 3 1
1 3 2 3 2 4 1 2 4
Where ifile.txt has 3 rows and 9 columns in this example. Desire output:
JavaScript
ofile.txt
1 1 3 1
2 3 7 4
3 6 12 6
4 8 14 9
5 11 17 11
6 12 21 15
7 16 22 16
8 21 25 18
9 22 26 22
.
.
.
Here first column is used for the serial number. So what I did is: I first converted into columns using
JavaScript
awk '{
for (i=1; i<=NF; i++) {
a[NR,i] = $i
}
}
NF>p { p = NF }
END {
for(j=1; j<=p; j++) {
str=a[1,j]
for(i=2; i<=NR; i++){
str=str" "a[i,j];
}
print str
}
}' ifile.txt > ifile1.txt
Then I use awk
JavaScript
awk '{print m1=$1+m1, m2=$2+m2, m3=$3+m3}' ifile1.txt > ofile.txt
I can’t proceed for the next step i.e. to insert a column of serial number. Also I can’t make it for arbitrary columns and rows.
Advertisement
Answer
for column of serial number
JavaScript
awk '{print i=i+1,m1=$1+m1, m2=$2+m2, m3=$3+m3}' ifile1.txt > ofile.txt
and for complete solution of your logic
JavaScript
awk '{for(i=1;i<=NF;i++){if(i>1)$i=$i+$(i-1);f[i]=f[i]" "$i}if(NF>n)n=NF}END{for(i=1;i<=n;i++)print i,f[i]}'