Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why uniq -c output with space instead of \t?

Tags:

shell

awk

uniq

I use uniq -c some text file. Its output like this:

123(space)first word(tab)other things
  2(space)second word(tab)other things

....

So I need extract total number(like 123 and 2 above), but I can't figure out how to, because if I split this line by space, it will like this ['123', 'first', 'word(tab)other', 'things']. I want to know why doesn't it output with tab?

And how to extract total number in shell? ( I finally extract it with python, WTF)

Update: Sorry, I didn't describe my question correctly. I didn't want to sum the total number, I just want to replace (space) with (tab), but it doesn't effect the space in words, because I still need the data after. Just like this:

123(tab)first word(tab)other things
  2(tab)second word(tab)other things
like image 961
MoreFreeze Avatar asked Jul 26 '12 13:07

MoreFreeze


3 Answers

Try this:

uniq -c | sed -r 's/^( *[^ ]+) +/\1\t/'
like image 159
Michał Kosmulski Avatar answered Nov 05 '22 08:11

Michał Kosmulski


Try:

uniq -c text.file | sed -e 's/ *//' -e 's/ /\t/'

That will remove the spaces prior to the line count, and then replace only the first space with a tab.

To replace all spaces with tabs, use tr:

uniq -c text.file | tr ' ' '\t'

To replace all continuous runs of tabs with a single tab, use -s:

uniq -c text.file | tr -s ' ' '\t'
like image 36
William Pursell Avatar answered Nov 05 '22 09:11

William Pursell


You can sum all the numbers using awk:

awk '{s+=$1}END{print s}'
like image 30
Igor Chubin Avatar answered Nov 05 '22 09:11

Igor Chubin