首页 > 解决方案 > 使用 awk 仅从第一个实例获取信息

问题描述

我正在使用 awk 从包含 300 个输出文件的目录中获取数据。

我要提取的大部分相关信息都是这种格式:

a bunch 
of text 
TOTAL ENERGY:   1234
a bunch 
of text 
not the same in
any way
DISPERSION COEFF:   5678
.
.
.

除了偶极矩,它看起来像:

Dipole Moment: [D]
     X:     1.2808      Y:     0.2908      Z:     1.0187     Total:     1.6622

此外,无论出于何种原因,偶极矩在文件中出现两次,方式与上述相同。信息完全一样。我想从此文件中提取总偶极矩。我有一个正在运行的脚本可以得到这个:

awk '/Dipole Moment: \[D\]/{found=1; next} found{print $NF; found=""; next} *.out 

但是,我得到两条相同偶极矩的线。

1. 如何避免这种情况?

其次,我想在列中排列所有这些信息。对于排列良好的属性,我有一种方法可以做到这一点,比如总能量和分散系数。这是我的脚本:

awk '/DISPERSION CORRECTION ENERGY/ {dee=$NF; next} /TOTAL ENERGY/{print $NF, dee;}' *.out

我得到的输出看起来像

5678 1234

但是,我无法在此表中安排偶极矩值。我应该如何解决这个问题?

出于测试目的:file1.out:

a bunch 
of text 
TOTAL ENERGY:   1234
a bunch 
of text 
not the same in
any way
DISPERSION COEFF:   5678
.
.
Dipole Moment: [D]
     X:     1.2808      Y:     0.2908      Z:     1.0187     Total:     1.6622
.
.
.
Dipole Moment: [D]
     X:     1.2808      Y:     0.2908      Z:     1.0187     Total:     1.6622

文件2.out:

a bunch 
of text 
TOTAL ENERGY:   4412
a bunch 
of text 
not the same in
any way
DISPERSION COEFF:   1111
.
.
Dipole Moment: [D]
     X:     1.28      Y:     0.08      Z:     1.87     Total:     1.22
.
.
.
Dipole Moment: [D]
     X:     1.28      Y:     0.08      Z:     1.87     Total:     1.22


期望的输出:

1234 5678 1.6622
4412 1111 1.22

标签: awktext-processing

解决方案


像这样的东西应该做你想做的(使用 GNU awk nextfile):

awk '
    FNR == 1 { delete f; inDipole=0 }
    { f[$1" "$2] = $NF }
    inDipole { print f["TOTAL ENERGY:"], f["DISPERSION COEFF:"], $NF; nextfile }
    /Dipole Moment:/ { inDipole = 1 }
' file{1,2}
1234 5678 1.6622
4412 1111 1.22

推荐阅读