1

I have a list as such below:

1,cat  
1,dog  
2,apple  
3,human

I'd like an output like this:

1,cat,dog  
2,apple  
3,human  

So value 1 from column 1 contains the value of cat and dog from column 2. Is that possible ?

  • It's quite straightforward in something like awk (concatenating the second column values into an array indexed by the first): why do you think you should be using uniq specifically? – steeldriver Mar 29 '15 at 3:57
  • i'm new to unix and still just ankle deep into awk so I just thought of unix -c – XY g Mar 29 '15 at 3:58
  • Are the numbers in the first column strictly ascending? – Janis Mar 29 '15 at 4:18
  • @steeldriver how would the pipeline look like ? – XY g Mar 29 '15 at 5:47
  • the question title is misleading, it has nothing to do with uniq. – 把友情留在无盐 Mar 29 '15 at 10:59
5

Assuming that the first column is strictly ordered:

$ awk -F, '$1==last {printf ",%s",$2;next} NR>1{print""} {last=$1;printf "%s",$0} END{print""}' file
1,cat,dog
2,apple
3,human

Alternatively, allowing the input lines in any order (and output lines in no guaranteed order):

$ awk -F, '{a[$1]=a[$1]","$2} END{for (i in a)print i a[i]}' file
1,cat,dog
2,apple
3,human
  • 1
    @XYg If this answer solved your issue, please take a moment and accept it by clicking on the check mark to the left. That will mark the question as answered and is the way thanks are expressed on the Stack Exchange sites. – terdon Mar 29 '15 at 12:43
1

In Perl:

$ perl -F',' -lane 'push @{$k{$F[0]}},@F[1..$#F]; 
                    END{$,=",";print $_,@{$k{$_}} for keys(%k)}' file 
2,apple
1,cat,dog
3,human

Or, for sorted output:

$ perl -F',' -lane 'push @{$k{$F[0]}},@F[1..$#F]; 
                    END{$,=",";print $_,@{$k{$_}} for sort keys(%k)}' file 
1,cat,dog
2,apple
3,human

This has the advantage of being able to deal with an arbitrary number of fields. If all your lines have 2 fields only, you can simplify to

perl -F',' -lane 'push @{$k{$F[0]}},$F[1]; 
                  END{$,=",";print $_,@{$k{$_}} for sort keys(%k)}' file 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.