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

Jon*_*nah 3 unix uniq

来自维基百科:

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.
Run Code Online (Sandbox Code Playgroud)

在我的机器上,它取计数并将其放在每一行的开头.我想要的是将它放在行尾,逗号后面.如何才能做到这一点?

例:

aa
aa
bb
cc
cc
dd
Run Code Online (Sandbox Code Playgroud)

应改为:

aa,2
bb,1
cc,2
dd,1
Run Code Online (Sandbox Code Playgroud)

jay*_*ngh 8

你可以试试这样的东西 -

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

要么

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

要么

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

要么

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

测试:

[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
Run Code Online (Sandbox Code Playgroud)

测试2:

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

TEST3:

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