如何使用 uniq -c 选项进行自定义格式化?

发布于 2024-12-28 07:14:40 字数 296 浏览 5 评论 0原文

来自维基百科:

uniq
-c 以默认样式生成输出报告,只不过每行前面都有其发生的次数计数。如果指定此选项,则 -u 和 -d 选项中的一个或两个都存在时将被忽略。

在我的机器上,它获取计数并将其放在每行的开头。我想要的是将其放置在行尾、逗号之后。这怎么能做到呢?

示例:

aa
aa
bb
cc
cc
dd

应更改为:

aa,2
bb,1
cc,2
dd,1

From wikipedia:

uniq
-c Generate an output report in default style except that each line is preceded by a count of the number of times it occurred. If this option is specified, the -u and -d options are ignored if either or both are also present.

On my machine it is taking the count number and putting it on the start of each line. What I want is for it to be placed at the end of the line, after a comma. How can this be done?

Example:

aa
aa
bb
cc
cc
dd

Should change to:

aa,2
bb,1
cc,2
dd,1

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

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

发布评论

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

评论(3

谁与争疯 2025-01-04 07:14:40

您可以尝试这样的操作 -

awk '{a[$1]++}END{for (i in a) print i,a[i] | "sort"}' OFS="," filename

awk -v OFS="," '{print $2,$1}' <(uniq -c file)

uniq -c file | awk '{printf("%s,%s\n",$2,$1)}'

while IFS=' +|,' read count text; do 
    echo "$text, $count"; 
done < <(uniq -c tmp)

测试:

[jaypal:~/Temp] cat file
aa
aa
bb
cc
cc
dd

[jaypal:~/Temp] awk '{a[$1]++}END{for (i in a) print i,a[i] | "sort"}' OFS="," file
aa,2
bb,1
cc,2
dd,1

测试2:

[jaypal:~/Temp] awk -v OFS="," '{print $2,$1}' <(uniq -c file)
aa,2
bb,1
cc,2
dd,1

测试3:

[jaypal:~/Temp] while IFS=' +|,' read count text; do 
echo "$text,$count"; 
done < <(uniq -c tmp)
aa,2
bb,1
cc,2
dd,1

You can try something like this -

awk '{a[$1]++}END{for (i in a) print i,a[i] | "sort"}' OFS="," filename

or

awk -v OFS="," '{print $2,$1}' <(uniq -c file)

or

uniq -c file | awk '{printf("%s,%s\n",$2,$1)}'

or

while IFS=' +|,' read count text; do 
    echo "$text, $count"; 
done < <(uniq -c tmp)

Test:

[jaypal:~/Temp] cat file
aa
aa
bb
cc
cc
dd

[jaypal:~/Temp] awk '{a[$1]++}END{for (i in a) print i,a[i] | "sort"}' OFS="," file
aa,2
bb,1
cc,2
dd,1

Test2:

[jaypal:~/Temp] awk -v OFS="," '{print $2,$1}' <(uniq -c file)
aa,2
bb,1
cc,2
dd,1

Test3:

[jaypal:~/Temp] while IFS=' +|,' read count text; do 
echo "$text,$count"; 
done < <(uniq -c tmp)
aa,2
bb,1
cc,2
dd,1
沙沙粒小 2025-01-04 07:14:40

像这样简单的事情,sedawk更容易

uniq -c inputfile.txt | sed -e 's/^ *\([0-9]\+\) \(.\+\)/\2,\1/'

Simple things like this, sed is easier than awk

uniq -c inputfile.txt | sed -e 's/^ *\([0-9]\+\) \(.\+\)/\2,\1/'

笑忘罢 2025-01-04 07:14:40

我会使用 awk 因为我发现它最具可读性

% uniq -c /path/to/input_file | awk -v OFS=',' '
{
    print $2, $1
}
'
aa,2
bb,1
cc,2
dd,1

I'd use awk as I find it most readable

% uniq -c /path/to/input_file | awk -v OFS=',' '
{
    print $2, $1
}
'
aa,2
bb,1
cc,2
dd,1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文