How do you do custom formatting with the uniq -c option?

5.5k Views Asked by At

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
3

There are 3 best solutions below

0
On BEST ANSWER

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
0
On

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
5
On

Simple things like this, sed is easier than awk

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