在AWK中打印数组中的所有元素

我想在 awk 中遍历数组中的所有元素并打印。这些值来自以下文件:

Ala     A       Alanine
Arg     R       Arginine
Asn     N       Asparagine
Asp     D       Aspartic acid
Cys     C       Cysteine
Gln     Q       Glutamine
Glu     E       Glutamic acid
Gly     G       Glycine
His     H       Histidine
Ile     I       Isoleucine
Leu     L       Leucine
Lys     K       Lysine
Met     M       Methionine
Phe     F       Phenylalanine
Pro     P       Proline
Pyl     O       Pyrrolysine
Ser     S       Serine
Sec     U       Selenocysteine
Thr     T       Threonine
Trp     W       Tryptophan
Tyr     Y       Tyrosine
Val     V       Valine
Asx     B       Aspartic acid or Asparagine
Glx     Z       Glutamic acid or Glutamine
Xaa     X       Any amino acid
Xle     J       Leucine or Isoleucine
TERM    TERM    termination codon

我试过这个:

awk 'BEGIN{FS="t";OFS="t"}{if (FNR==NR) {codes[$1]=$2;} else{next}}END{for (key in codes);{print key,codes[key],length(codes)}}' $input1 $input2

并且输出始终是Cys C 27,当我替换为时codes[$1]=$2codes[$2]=$1我得到M Met 27.

如何让我的代码按顺序打印出所有值?我不明白为什么我的代码有选择地只打印出一个元素,当我可以知道数组长度为预期的 27 时。(为了保持我的代码最少,我已经排除了其中的代码else{next}- 否则我只想codes在保留else{***}命令的同时打印数组中的所有元素)

根据如何查看 awk 数组中的所有内容?, 上面的语法应该可以工作。我在这里尝试过echo -e "1 2n3 4n5 6" | awk '{my_dict[$1] = $2};END {for(key in my_dict) print key " : " my_dict[key],": "length(my_dict)}',效果很好。

回答

使用您显示的示例和尝试,请尝试在 GNU 中进行以下、编写和测试awk

awk '
BEGIN{
  FS=OFS="t"
}
{
  codes[$1]=$2
}
END{
  for(key in codes){
     print key,codes[key],length(codes)
  }
}' Input_file

将在几分钟内添加详细的解释和 OP 的失误。

说明:为以上添加详细说明。

awk '                     ##Starting awk program from here.
BEGIN{                    ##Starting BEGIN section from here.
  FS=OFS="t"             ##Setting FS and OFS as TAB here.
}
{
  codes[$1]=$2            ##Creating array codes with index of 1st field and value of 2nd field
}
END{                      ##Starting END block of this program from here.
  for(key in codes){      ##Traversing through codes array here.
     print key,codes[key],length(codes)  ##Printing index and value of current item along with total length of codes.
  }
}' Input_file             ##Mentioning Input_file name here.


以上是在AWK中打印数组中的所有元素的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>