LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Compressing a two columned list (https://www.linuxquestions.org/questions/linux-newbie-8/compressing-a-two-columned-list-4175470630/)

krmarshall87 07-23-2013 10:34 AM

Compressing a two columned list
 
I have a list of instances in a server cluster and their matching hostname:

Code:

CLUSTER-A HOST1
CLUSTER-A HOST2
CLUSTER-A HOST3
CLUSTER-A HOST4
CLUSTER-B HOST1
CLUSTER-B HOST2
.
.

I'm sure there is a simpler command (awk or sed) that would get me:

Code:

CLUSTER-A HOST1 HOST2 HOST3 HOST4
CLUSTER-B HOST1 HOST2 HOST3 HOST4
.
.

Currently, I write it to an array and process each string- a real pain, so am curious as to a better method.

From my searches (tough to search for something I can't put a name to), I couldn't find much. But I'm sure this is a common issue.

jpollard 07-23-2013 11:33 AM

Try:
Code:

#!/bin/sh

awk '
BEGIN {val="";}
      {
        if (val == $1) printf(" %s",$2);
        else {
              if (val != "") printf("\n");
              val=$1;
              printf("%s %s",$1,$2);
        }
      }
END    { printf("\n");}'

Just redirect the input data into the script, and redirect the output to the result.

NOTE: This assumes the input is sorted.

Another note: I see your output has a "CLUSTER-B HOST1 HOST2 HOST3 HOST4", but the input has no such data.

krmarshall87 07-23-2013 12:06 PM

I was only putting in an example the . . were to imply further data, so your code works great and does exactly what is needed especially since I do a sort prior. Thanks much for your help!


All times are GMT -5. The time now is 09:35 PM.