首页 > 解决方案 > 文件中某个块中的列总和:awk 可以这样做吗?

问题描述

我想处理文件中的某个块。我想要的工作是对块中的列求和。可以使用awk吗?还是其他指挥官更好?

  1. 找到一个 str1 (样本中的“原子”)
  2. 然后开始对第八列求和 $7
  3. 如果您找到 str2 (示例中的“债券”),则停止

目前我能做的是

awk 'BEGIN { i=0; sum=0.0;} { if ($9) { print $7; sum+=$7;}} END {printf "total charge is %10.6f", sum}'

在这种情况下,如果某处的第 9 列中还有另一个值,那将是错误的。

[样本文件 w。1500线]

.... many lines
[ atoms ]
;   nr  type  resi  res  atom  cgnr     charge      mass       ; qtot   
 1   c3     1     2     C    1     0.138400     12.01000 ; qtot 0.138
 2   os     1     2     O    2    -0.436600     16.00000 ; qtot -0.298
 3   c3     1     2    C1    3    -0.093400     12.01000 ; qtot -0.392
 4   c3     1     2    C2    4    -0.076400     12.01000 ; qtot -0.468

[ bonds ]
;   ai     aj funct   r             k
     1      2   1    1.4316e-01    2.5824e+05 ;      C - O
.... many lines are followed

标签: awk

解决方案


你可以试试这个 awk 脚本:

awk '$0=="[ atoms ]"{go=1}                         # Set flag to start the sum
     go{sum+=$7}                                   # If flag set sum the 8th column
     $0=="[ bonds ]"{go=0}                         # End the sum
     END{printf "total charge is %10.6f\n",sum}    # Print result
' file

推荐阅读