下午好,
我想知道如何获得B列中最常出现并存储到变量中的值,在并列的情况下,根据B列从A列中获得最低值。这些列来自CSV,由","分隔B栏总是用大写字母表示。
不允许grep、awk、sed、csvkit
文件.csv->
A,B
4,AA
3,AA
2,BB
1,BB
我试过了:
var=$(tail +2 file.csv | cut -d , -f2 | sort | uniq -c)
echo $var
2 AA 2 BB
不幸的是,我期待着这样的结果(没有显示重复次数最多的字符串,也没有在平局的情况下显示正确的字符串;这是因为BB在A列中的值最低,数字为1,而AA的值为3(:
echo $var
BB
#!/bin/bash
declare -A count min
declare -i max_count=0 max_value
# loop 1: get the count and the minimum value for each B
# and find the max value for A
{
read header
while IFS=, read -r a b; do
((count[$b]++))
((count[$b] > max_count)) && max_count=${count[$b]}
if [[ ! -v min[$b] ]] || ((a < min[$b])); then min[$b]=$a; fi
if [[ -z $max_value ]] || ((max_value < a)); then max_value=$a; fi
done
} < file.csv
# loop 2: find the B's with the max count
declare -a candidates
for c in "${!count[@]}"; do
if ((count[$c] == max_count)); then
candidates+=("$c")
fi
done
# loop 3: find the minimum A value among the candidates
min_value=$max_value
for c in "${candidates[@]}"; do
((min[$c] < min_value)) && min_value=${min[$c]}
done
# loop 4: print out the candidates with the minimum A value
for c in "${candidates[@]}"; do
((min[$c] == min_value)) && echo "$c"
done