Reputation: 45
I am trying to achieve the following, but I am completely new in the topic of programming, and I am getting crazy. I have seen many examples where it is explained how to make the sum of a column or so, but never how to add values from the same row. I have tried to do something with the awk
command, but it was completely useless...
I have this input:
10000 4.32078125e-05 2.319742728e-05 -1.626118465e-06 2.116442767e-05 2.824876608e-06 -2.008498137e-07 1.378852315e-11 -2.461344776e-11 -1.185369303e-11 -4.711965783e-11 -7.488327241e-10 -1.133857758e-08
In order not to get crazy with so many numbers, it is something like:
#Iteration #FpX #FpY #FpZ #FvX #FvY #FvZ #MpX #MpY #MpZ #MvX #MvY #MvZ
And I need the following output (first line is text):
Iteration FX FY FZ MX MY MZ
#Iteration #FpX+#FvX #FpY+#FvY #FpZ+#FvZ #MpX+#MvX #MpY+#MvY #MpZ+#MvZ
Upvotes: 1
Views: 57
Reputation: 67231
If you donot need the header this works:
perl -lane 'push @a,$F[0];
for($i=1;$i<13;$i++){
$i+=3 if($i==4);
push @a,$F[$i]+$F[$i+3]}
print "@a"' your_file
Tested below:
> perl -lane 'push @a,$F[0];for($i=1;$i<13;$i++){$i+=3 if($i==4);push @a,$F[$i]+$F[$i+3]}print "@a"' temp
10000 6.437224017e-05 2.6022303888e-05 -1.8269682787e-06 -3.333113468e-11 -7.7344617186e-10 -1.135043127303e-08 -4.711965783e-11 -7.488327241e-10 -1.133857758e-08
Upvotes: 0
Reputation: 45576
You can reference the <N>
th column (field) via $<N>
, e.g. $1
which you can use to do your arithmetics:
$ cat foo.input
10000 4.32078125e-05 2.319742728e-05 -1.626118465e-06 2.116442767e-05 2.824876608e-06 -2.008498137e-07 1.378852315e-11 -2.461344776e-11 -1.185369303e-11 -4.711965783e-11 -7.488327241e-10 -1.133857758e-08
10001 1 2 3 4 5 6 7 8 9 10 11 12
$ awk \
'BEGIN { printf "%-11s %-12s %-12s %-12s %-12s %-12s %-12s\n", "Iteration", "FX", "FY", "FZ", "MX", "MY", "MZ" }
NF { printf "%-11s %-12s %-12s %-12s %-12s %-12s %-12s\n", $1, $2+$5, $3+$6, $4+$7, $8+$11, $9+$12, $10+$13 }' foo.input
Iteration FX FY FZ MX MY MZ
10000 6.43722e-05 2.60223e-05 -1.82697e-06 -3.33311e-11 -7.73446e-10 -1.13504e-08
10001 5 7 9 17 19 21
Upvotes: 2