
B열의 최대값을 찾고 싶습니다.그리고B열 값이 최대값의 20% 이상인 모든 행을 유지합니다.
입력 데이터
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
원하는 출력
A B C D E
2 79 56 SD L
9 60 37 KD G
을 사용해 보았지만 awk 'BEGIN {max = 0} {if ($2>max) max=$2} END {if ($2 >= (0.1*max)) print}' file_in > file_out
파일의 마지막 줄만 인쇄됩니다.
답변1
END{ }
파일을 두 번 스캔 하려면 모든 행을 배열에 저장해야 합니다 . 따라서 모든 값과 행을 저장하십시오.
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
답변2
그리고밀러:
1) 예쁜 인쇄 데이터:
$> mlr --from data --ipprint --otsv cat
A B C D E
2 79 56 SD L
9 60 37 KD G
2) 필드의 최대값을 B
필드에 추가합니다 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) 필터 라인의 경우 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) 그런 다음 다시 cut
출발합니다 B_max
.
$> 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