rpf
1
Hello friends, could you help me about problem with my data lines. I suppose a simple awk code may help me.
I have following data lines: (first line including 3 numbers and then a matrices of 4x10)
500 40 9
1 A B 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 Z P R
How can I convert this format to
first line sum of 3 numbers at the first line ---> 549
second line is converted to 1x40 ----> 1 A B 4 5 6 7 8 9 ..... Z P R
Could anyone help ?
thanks
Yoda
2
awk ' BEGIN { sum=0; }
NR==1 { for(i=1;i<=NF;i++) { sum+=$i; } print sum; }
NR>1 { for(i=1;i<=NF;i++) printf "%s ", $i }
END { printf "\n";
} ' filename
1 Like
rpf
3
thank you very much bipinajith ,
what if I have multiple as follows, is it possible to do each of them seperately
5 2 3
-12.108 -11.789 -5.196 -4.370 -3.344 -2.229 -1.465 -0.347 -0.325 2.456
2.855 4.105 4.569 5.902 7.791 7.950 8.750 9.383 10.041 10.160
10.755 11.441 11.827 12.302 12.847 13.816 15.849 15.904 16.213 16.383
17.158 17.705 18.715 19.221 19.330 19.411 19.696 20.122 20.142 20.417
7 4 8
-12.118 -11.796 -5.181 -4.356 -3.345 -2.225 -1.463 -0.351 -0.334 2.454
2.842 4.093 4.566 5.937 7.785 7.924 8.741 9.360 10.046 10.129
10.845 11.461 11.850 12.233 12.942 13.811 15.853 15.860 16.200 16.399
17.192 17.707 18.708 19.149 19.302 19.381 19.664 20.017 20.089 20.375
I mean
11
-12.108 -11.789 -5.196 -4.370 -3.344 -2.229 -1.465 -0.347 -0.325 2.456 2.855 ....
19
-12.118 -11.796 -5.181 -4.356 -3.345 -2.225 -1.463 -0.351 -0.334 2.454 2.842 ...
is it possible ?
Yoda
4
Assuming every new set starts with 3 numbers:-
awk ' BEGIN { sum=0; }
NF==3 { for(i=1;i<=NF;i++) { sum+=$i; } if(NR==1) printf "%s\n", sum; else printf "\n%s\n", sum; sum=0;}
NF>3 { for(i=1;i<=NF;i++) { printf "%s ", $i; } ; }
END { printf "\n";
} ' filename
1 Like
rpf
5
Thank you very much... It works perfect.
One last question. If you don"t have time forget it
instead of simple sum of 3 numbers i.e. a+b+c, is it possible to get Sqrt(axa+bxb+cxc) with this code ?
which part should I change ?
thank you for your time
Yoda
6
You have to change 2nd line to:
NF==3 { for(i=1;i<=NF;i++) { sum+=($i*$i); } if(NR==1) printf "%s\n", sqrt(sum); else printf "\n%s\n", sqrt(sum); sum=0;}
1 Like
rpf
7
thanks bipinajith
It works perfect...
thank you for your time