【问题标题】:Counting strings from array in bash在bash中计算数组中的字符串
【发布时间】:2014-07-23 07:03:50
【问题描述】:

我正在将awk 的输出写入 bash 中的数组,如下所示:

ARR=$(( awk '{print $2}' file.txt ))

想象一下 file.txt 的内容是:

A B
A B
A C
A D
A C
A B

我想要的是第二列中每个字符串的重复次数,例如:

B: 3
C: 2
D: 1

欢迎使用任何其他解决方案,而不是 arraysawk

【问题讨论】:

    标签: arrays bash awk counter


    【解决方案1】:

    使用 awk 你可以做到:

    awk '{c[$2]++} END{for (i in c) print i ":", c[i]}' file
    B: 3
    C: 2
    D: 1
    

    【讨论】:

    • 替代方案是:sort -k2 file | uniq -f1 -c |awk '{print $3 ":", $1}'
    【解决方案2】:

    我找到的其他解决方案:

    awk '{print $2}' file.txt | sort | uniq -c | sort -nr | while read count name
    do
            if [ ${count} -gt 1 ]
            then
                    echo "${name} ${count}"
            fi
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-04-20
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2014-03-03
      • 1970-01-01
      相关资源
      最近更新 更多