ubuntu 如何在BASH中获取CSV列的最多计数值?

qv7cva1a  于 2022-11-02  发布在  其他
关注(0)|答案(1)|浏览(193)

下午好,
我想知道如何获取B列中最常出现的值并将其存储到变量中,如果出现平局,则根据B列从A列中获取最低值。这些列来自CSV,由','分隔。B列始终以大写字母显示。
不允许使用grep、awk、sed、csvkit
文件.csv-〉

A,B
4,AA
3,AA
2,BB
1,BB

我试探着:
第一个
不幸的是,我期待的是这样的东西(没有显示重复最多的字符串,并显示正确的字符串,以防领带;这是因为BB在A列中具有最低的值,与AA的值3相比,其数字为1):
第一个

nzrxty8p

nzrxty8p1#


# !/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

相关问题