user1536457
user1536457

Reputation: 1

joining 2 lines based on first field

Hi i have something like this in a file

12345   aaaaaaaaaabbbbbbbbbb 
23456   bbcbcbbgyhuhuhhhhhhh 
12345   7ijkunmmnniiiiiiii
23456   bbcbcbbgyhuhsdrfrrhhhv

I want to merge lines into a single line based on first

field i,e.,

12345   aaaaaaaaaabbbbbbbbbb 12345   7ijkunmmnniiiiiiii
23456 bbcbcbbgyhuhuhhhhhhv 23456   bbcbcbbgyhuhsdrfrrhh

can any one let me know how to do that?

Upvotes: 0

Views: 102

Answers (3)

Thor
Thor

Reputation: 47239

An awk alternative:

awk '
  { A[$1] = A[$1] $0 " " } 
  END { for (k in A) print A[k] }' infile

Concatenates each line on to an associative array with $1 as the key.

Upvotes: 1

Pavel Vlasov
Pavel Vlasov

Reputation: 3465

use strict;

open my $fh, '<your_file'
   or die "cant open file $!";

my %result; # result hash

# read file line by line
while (my $line = <$fh>) {
    chomp $line;

    # check format
    if ( $line =~ m/^(\d+)\s+(.*?)$/x ) {

        # add value to anonymous array in hash
        $result{$1} = [] unless exists $result{$1};
        push @{$result{$1}}, $2;
    }
}

# print result
while (my ($key, $values) = each %result) {

   printf "%s ", $key;
   for my $value (@$values) {

       printf "%s,", $value;
   }
}

close $fh;

Upvotes: 1

cdtits
cdtits

Reputation: 1128

while (<DATA>) {
    ($x, $y) = split;
    push @{$lines{$x}}, $y;
}

while (($x, $y) = each %lines) {
    print "$x\t$_\t" for @{$y};
    print "\n";
}

__DATA__
12345   aaaaaaaaaabbbbbbbbbb 
23456   bbcbcbbgyhuhuhhhhhhh 
12345   7ijkunmmnniiiiiiii
23456   bbcbcbbgyhuhsdrfrrhhhv

Upvotes: 1

Related Questions