如何获取第一列的唯一元素并将其存储在数组中? [英] How to get the unique elements of the first column and store it in an array?

查看:49
本文介绍了如何获取第一列的唯一元素并将其存储在数组中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提取file1"中这两行之间的第一列(%BLOCK position_frac & %ENDBLOCK position_frac).

I want to extract the first column between this two lines (%BLOCK positions_frac & %ENDBLOCK positions_frac) in "file1".

%BLOCK positions_frac
Si        0.5303000000000000  0.0000000000000000  0.3333000000000000
Si        0.0000000000000000  0.5303000000000000  0.6666299999999999
Si        0.4697000000000000  0.4697000000000000  0.9999700000000000
O         0.1462000000000000  0.4142000000000000  0.8810000000000000
O         0.7320000000000000  0.5858000000000000  0.7856700000000000
O         0.5858000000000000  0.7320000000000000  0.2143300000000000
O         0.2680000000000000  0.8538000000000000  0.5476700000000000
O         0.4142000000000000  0.1462000000000000  0.1190000000000000
O         0.8538000000000000  0.2680000000000000  0.4523300000000000
%ENDBLOCK positions_frac

我可以使用:

awk '/%BLOCK\ positions_frac/{flag=1;next}/%ENDBLOCK\ positions_frac/{flag=0}flag' file1

然后我想将第一列存储在一个数组中,但不是等价的

Then I want to store the first column in an array but of the non-equivalent ones

预期输出:

array= ["Si", "O"]

推荐答案

这是如何编写 awk 部分的(如果您愿意,可以将其全部压缩回 1 行):

This is how to write the awk part (squeeze it all back onto 1 line if you like):

$ awk '
    /%ENDBLOCK positions_frac/ { inBlock=0 }
    inBlock && !seen[$1]++     { print $1 }
    /%BLOCK positions_frac/    { inBlock=1 }
' file
Si
O

然后就是将输出保存在shell数组中:

then it's just this to save the output in a shell array:

arr=( $(awk '...' ) )

这篇关于如何获取第一列的唯一元素并将其存储在数组中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆