awk - 文件中某个块中的列总和:awk 可以这样做吗?
问题描述
我想处理文件中的某个块。我想要的工作是对块中的列求和。可以使用awk吗?还是其他指挥官更好?
- 找到一个 str1 (样本中的“原子”)
- 然后开始对第八列求和 $7
- 如果您找到 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 '$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
推荐阅读
- python - Gitlab-CI 使用令牌而不是 ssh 密钥从 setup.py 克隆私有仓库?
- ios - Swift UIDocument 保存不可靠
- java - 在 Wildfly/JBoss 应用服务器上以编程方式创建 Web 服务
- vba - VLookup 的问题和可能的解决方法
- python - 如果我们从用户那里获得输入,如果我们要求输入密码,如何获得输入为 *(星号)?
- python - 如何在pyqt5中获取不带引号的文件路径
- google-apps-script - 我需要一个脚本,它会在单元格值更改时自动触发 sendEmail 函数
- kubernetes - 获取停留在终止状态超过 10 分钟的 Pod 列表,并在 Ansible 中将其删除
- android - Android:如何从库回调到主应用程序项目?
- linux - Bash one-liner 保存到文件然后使用内容