O arquivo txt de entrada se parece com (há mais colunas no arquivo txt real):
target_id length eff_length tot_counts uniq_counts est_counts eff_counts
mthl7 61 0 0 0 0 0
loqs 72 0 0 0 0 0
CG45085 58 0 0 0 0 0
CG18317 4978 1430.739479 91 0 30.333333 105.539363
CG18317 4978 1430.739479 91 0 30.333333 105.539363
CG18317 4978 1430.739479 91 0 30.333333 105.539363
para a coluna 1 quando eles têm o mesmo id (por exemplo, CG18317), quero somar os valores no restante das colunas. Então a saída ficaria assim:
target_id length eff_length tot_counts uniq_counts est_counts eff_counts
mthl7 61 0 0 0 0 0
loqs 72 0 0 0 0 0
CG45085 58 0 0 0 0 0
CG18317 14934 4292.218437 273 0 90.999999 316.618089
Tentei usar comandos como:
awk -F" "
'{a[$1]+=$4;b[$1]+=$5;c[$1]+=$6;d[$1]+=$7;e[$1]+=$8;f[$1]+=$9;g[$1]+=$10;h[$1]+=$11;i[$1]+=$12;j[$1]+=$14;}END{for (i in a) print i" "a[i]" "b[i]" "c[i]" "d[i]" "e[i]" "f[i]" "g[i]" "h[i]" "i[i]" "j[i]}' temp2.txt
A mensagem de erro é:
awk: can't assign to i; it's an array name.
input record number 7, file temp2.txt
source line number 1
Isso é devido ao cabeçalho? Como devo ignorar a 1ª linha?
Tentei respostas para perguntas semelhantes encontradas aqui, mas também não funcionou.
Responder1
$ awk 'NR==1{print;next} {for (i=2;i<=NF;i++) {a[$1][i]+=$i}} END{ \
for (j in a) {s=j; for (i=2;i<=NF;i++) {s=s" "a[j][i]}; print s}}' file
target_id length eff_length tot_counts uniq_counts est_counts eff_counts
mthl7 61 0 0 0 0 0
loqs 72 0 0 0 0 0
CG18317 14934 4292.22 273 0 91 316.618
CG45085 58 0 0 0 0 0
Se você quiser manter as linhas na mesma ordem, será necessário um pouco mais de código:
$ awk 'NR==1{print;next} {if ($1 in seen); else b[c++]=$1; seen[$1]=1; \
for (i=2;i<=NF;i++) {a[$1][i]+=$i}} END{for (j=0;j<c;j++) {s=b[j]; \
for (i=2;i<=NF;i++){s=s" "a[b[j]][i]}; print s}}' file | column -t
target_id length eff_length tot_counts uniq_counts est_counts eff_counts
mthl7 61 0 0 0 0 0
loqs 72 0 0 0 0 0
CG45085 58 0 0 0 0 0
CG18317 14934 4292.22 273 0 91 316.618
Acima, também canalizamos a saída para column -t
obter colunas alinhadas.
Comandos em formato adequado para copiar e colar
Os comandos acima foram distribuídos por vários para facilitar a visualização. Se você deseja copiar e colar os comandos, use estas versões:
awk 'NR==1{print;next} {for (i=2;i<=NF;i++) {a[$1][i]+=$i}} END{ for (j in a) {s=j; for (i=2;i<=NF;i++) {s=s" "a[j][i]}; print s}}' file
E:
awk 'NR==1{print;next} {if ($1 in seen); else b[c++]=$1; seen[$1]=1; for (i=2;i<=NF;i++) {a[$1][i]+=$i}} END{for (j=0;j<c;j++) {s=b[j]; for (i=2;i<=NF;i++){s=s" "a[b[j]][i]}; print s}}' file | column -t
Não-GNUawk
Tentar:
awk 'NR==1{print;next} {if ($1 in seen); else b[c++]=$1; seen[$1]=1; for (i=2;i<=NF;i++) {a[$1","i]+=$i}} END{for (j=0;j<c;j++) {s=b[j]; for (i=2;i<=NF;i++){s=s" "a[b[j]","i]}; print s}}' file | column -t