Is it possible to transform this:
1 Alice
1 Bob
1 Cary
2 Dan
3 Eve
3 Fred
into this:
1 Alice,Bob,Cary
2 Dan
3 Eve,Fred
using shell? (without Perl, Ruby, Python etc)
Is it possible to transform this:
1 Alice
1 Bob
1 Cary
2 Dan
3 Eve
3 Fred
into this:
1 Alice,Bob,Cary
2 Dan
3 Eve,Fred
using shell? (without Perl, Ruby, Python etc)
Using associative arrays in bash version 4:
declare -A ary
while read line; do
set -- $line
ary[$1]+="$2,"
done < input_file
for key in ${!ary[@]}; do
printf "%s %s\n" $key ${ary[$key]%,} # the "%," strips the trailing comma
done
Crap I couldn't resist the challenge. Here's my solution in shell (bash to be exact) as a oneliner:
k=0; while read i j; do if [ $k -eq $i ]; then echo -n ",$j"; \
else [ $k -gt 0 ] && echo; echo -n "$i $j"; k=$i; fi; done \
</tmp/infile; echo
which produces the desired output, properly formatted:
1 Alice,Bob,Cary
2 Dan
3 Eve,Fred
Assumptions:
If #2 is not valid, you need to run the input through sort(1)
first with a numeric sort to put it in the proper order.
If I find out I just answered your homework I will be extremely annoyed. My only consolation is that if your teacher sees what I wrote they will think you are nuts.
This one over at stackoverflow is very similar and has some good answers: https://stackoverflow.com/questions/380817/best-way-to-simulate-group-by-from-bash