
Gostaria de encontrar o valor máximo da coluna BEmantenha todas as linhas onde os valores da coluna B são 20% ou mais do máximo.
DADOS DE ENTRADA
A B C D E
2 79 56 SD L
1 09 67 JK S
9 60 37 KD G
0 10 47 SO E
SAÍDA DESEJADA
A B C D E
2 79 56 SD L
9 60 37 KD G
Eu tentei usar, awk 'BEGIN {max = 0} {if ($2>max) max=$2} END {if ($2 >= (0.1*max)) print}' file_in > file_out
mas isso só imprime o que parece ser a última linha do meu arquivo.
Responder1
Você precisa salvar todas as linhas em um array para poder percorrê-las novamente no arquivo END{ }
. Ou, alternativamente, verifique o arquivo duas vezes. Então, salvando todos os valores e linhas:
awk 'NR == 1 {header=$0; next} # save the header
{ lines[NR] = $0; values[NR] = $2; # save the line and 2nd field
if ($2 > max) max = $2; } # update max
END { print header; # in the end, print the header
for (i = 1 ; i <= NR ; i++) { # (we skipped line 0)
if (values[i] >= max * 0.2) # print lines where $2 was high enough
print lines[i]; } } ' file_in
Responder2
Commoleiro:
1) Dados de impressão bonita:
$> mlr --from data --ipprint --otsv cat
A B C D E
2 79 56 SD L
9 60 37 KD G
2) Adicione o máximo de campo B
a campo B_max
:
$> mlr --from data --ipprint --otsv stats1 -a max -f B -s -F
A B C D E B_max
2 79 56 SD L 79.000000
1 09 67 JK S 79.000000
9 60 37 KD G 79.000000
0 10 47 SO E 79.000000
3) Filtrar linhas onde B >= B_max * 0.2
:
$> mlr --from data --ipprint --otsv stats1 -a max -f B -s -F then filter '$B >= $B_max*0.2'
A B C D E B_max
2 79 56 SD L 79.000000
9 60 37 KD G 79.000000
4) Então cut
vá embora B_max
novamente:
$> mlr --from data --ipprint --otsv stats1 -a max -f B -s -F then filter '$B >= $B_max*0.2' then cut -x -f B_max
A B C D E
2 79 56 SD L
9 60 37 KD G