bash - 对列中的字符进行计数和索引

标签 bash indexing awk grep

我有一个包含几列的文件 system.xyz:

          43
  Built with Packmol
  O           37.536208       36.873149        9.514500
  C           37.768292       35.784076       10.014380
  N           37.749829       34.667899        9.235406
  C           38.014779       33.336113        9.750827
  C           37.921777       32.283049        8.635104
  C           38.203826       30.885654        9.187454

并且需要将它们更改为:

@atom:o1 @mol: $atom:O 0 37.536208 36.873149 9.514500
@atom:c1 @mol: $atom:C 0 37.768292 35.784076 10.014380
@atom:n1 @mol: $atom:N 0 37.749829 34.667899 9.235406
@atom:c2 @mol: $atom:C 0 38.014779 33.336113 9.750827
@atom:c3 @mol: $atom:C 0 37.921777 32.283049 8.635104
@atom:c4 @mol: $atom:C 0 38.203826 30.885654 9.187454

我已经成功地使用了这个 grep -A43 内置 system.xyz | awk '{print "@atom:"tolower($1), "@mol: $atom:"$1,"0",$2,$3,$4}'

@atom:built @mol: $atom:Built 0 with Packmol 
@atom:o @mol: $atom:O 0 37.536208 36.873149 9.514500
@atom:c @mol: $atom:C 0 37.768292 35.784076 10.014380
@atom:n @mol: $atom:N 0 37.749829 34.667899 9.235406
@atom:c @mol: $atom:C 0 38.014779 33.336113 9.750827
@atom:c @mol: $atom:C 0 37.921777 32.283049 8.635104
@atom:c @mol: $atom:C 0 38.203826 30.885654 9.187454

但我必须手动输入第一列每个字符的索引。有没有办法对第一列中的字符进行计数和索引?

最佳答案

试试这个:

awk '
    BEGIN {fmt = "@atom:%s%d @mol: $atom:%s 0"}
    {$1 = sprintf(fmt, tolower($1), ++count[tolower($1)], $1)}
    1
'

关于bash - 对列中的字符进行计数和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64377574/

相关文章:

bash - awk、System() 函数、与 shell 交互

python - Numpy:多维索引。逐行无循环

regex - 如何使用 grep/sed/awk 从文本文件开头删除模式

linux - 为什么我不能将文件从 ~/process.desktop 移动到 ~/.config/autostart/?

linux - 在 bash 中捕获多个并行的 grep 输出

ruby-on-rails - Elasticsearch术语过滤器速度慢

xml - 如何使用 awk 在多个文件中第一次匹配模式后插入多行

bash - 如何在 bash 中仅替换单个换行符?

linux - nohup 是否跨管道工作?

sql - 考虑到动态查询的索引大平面表的最佳方式