下午好,
我想知道如何獲取 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
不幸的是,我期待這樣的事情(沒有顯示重復的最多字串并在平局的情況下顯示正確的字串;那是因為與 AA 的值 3 相比,BB 在 A 列中的值最低,數字為 1):
echo $var
BB
uj5u.com熱心網友回復:
#!/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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/523623.html
下一篇:用于從字串s-pub-comtec-sap-product-app-1.0.0-mule-app.war中獲取值的AWK命令
