Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing delimiter of the uniq command

Tags:

uniq

I'd like the output of the uniq command to be comma separated, so that instead of:

     30 hello
     31 world
     36 hey_there
    142 i_am_bigest

I'll get:

30,hello
31,world
36,hey_there
142,i_am_biggest

My input has no spaces, but just using sed or tr can be a problem since the number of leading spaces varies according to the number of decimal digits in the count.

like image 443
eran Avatar asked Jun 10 '13 06:06

eran


2 Answers

Pipe the output to

sed -e 's/^ *//;s/ /,/'

This first removes the leading spaces (^ *) then replaces the first space with a comma.

like image 77
nneonneo Avatar answered Oct 14 '22 06:10

nneonneo


man uniq (at least on Mac OS X, aka BSD) does not give any way to handle that. Your best bet is probably sed:

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

The output from uniq -c consists of some blanks, a number, a blank, and the input string.

The basic idea is that the sed script looks for an arbitrary number of blanks, a number and a blank, and replace it by the number and a comma. Looking at the POSIX specification for uniq, the output is not supposed to have leading blanks (the printf() format should be "%d %s"), but leading blanks are normal in practice (for small enough repeat counts; on Mac OS X, the output printf() format is effectively "%5d %s").

like image 45
Jonathan Leffler Avatar answered Oct 14 '22 07:10

Jonathan Leffler