计算 bash 中每行只有一个字符串的唯一字符串

发布于 2024-12-29 06:00:28 字数 158 浏览 0 评论 0原文

给定输入文件,

z
b
a
f
g
a
b
...

我想输出每个字符串出现的次数,例如:

z 1
b 2
a 2
f 1
g 1

如何在 bash 脚本中完成此操作?

Given input file

z
b
a
f
g
a
b
...

I want to output the number of occurrences of each string, for example:

z 1
b 2
a 2
f 1
g 1

How can this be done in a bash script?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

漫雪独思 2025-01-05 06:00:28

您可以排序输入并传递到 uniq -c< /a>:

$ sort input_file | uniq -c
 2 a
 2 b
 1 f
 1 g
 1 z

如果您想要右侧的数字,请使用awk 切换它们:

$ sort input_file | uniq -c | awk '{print $2, $1}'
a 2
b 2
f 1
g 1
z 1

或者,在 awk 中完成整个操作:

$ awk '
{
    ++count[$1]
}
END {
    for (word in count) {
        print word, count[word]
    }
}
' input_file
f 1
g 1
z 1
a 2
b 2

You can sort the input and pass to uniq -c:

$ sort input_file | uniq -c
 2 a
 2 b
 1 f
 1 g
 1 z

If you want the numbers on the right, use awk to switch them:

$ sort input_file | uniq -c | awk '{print $2, $1}'
a 2
b 2
f 1
g 1
z 1

Alternatively, do the whole thing in awk:

$ awk '
{
    ++count[$1]
}
END {
    for (word in count) {
        print word, count[word]
    }
}
' input_file
f 1
g 1
z 1
a 2
b 2
咆哮 2025-01-05 06:00:28
cat text | sort | uniq -c

应该做这份工作

cat text | sort | uniq -c

should do the job

吹泡泡o 2025-01-05 06:00:28

尝试:

awk '{ freq[$1]++; } END{ for( c in freq ) { print c, freq[c] } }' test.txt

其中 test.txt 是您的输入文件。

Try:

awk '{ freq[$1]++; } END{ for( c in freq ) { print c, freq[c] } }' test.txt

Where test.txt would be your input file.

万水千山粽是情ミ 2025-01-05 06:00:28

这是仅 bash 版本(需要 bash 版本 4),使用 关联数组

#! /bin/bash

declare -A count
while read val ; do
    count[$val]=$(( ${count[$val]} + 1 ))
done < your_intput_file # change this as needed

for key in ${!count[@]} ; do
    echo $key ${count[$key]}
done

Here's a bash-only version (requires bash version 4), using an associative array.

#! /bin/bash

declare -A count
while read val ; do
    count[$val]=$(( ${count[$val]} + 1 ))
done < your_intput_file # change this as needed

for key in ${!count[@]} ; do
    echo $key ${count[$key]}
done
盛夏尉蓝 2025-01-05 06:00:28

这可能对您有用:

cat -n file | 
sort -k2,2 | 
uniq -cf1 | 
sort -k2,2n | 
sed 's/^ *\([^ ]*\).*\t\(.*\)/\2 \1/'

这会按照每个字符串出现的顺序输出它们出现的次数。

This might work for you:

cat -n file | 
sort -k2,2 | 
uniq -cf1 | 
sort -k2,2n | 
sed 's/^ *\([^ ]*\).*\t\(.*\)/\2 \1/'

This output the number of occurrences of each string in the order in which they appear.

等风来 2025-01-05 06:00:28

您可以使用sort filename | uniq -c

查看uniq 上的维基百科页面

You can use sort filename | uniq -c.

Have a look at the Wikipedia page on uniq.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文