嗨我在文件中有这样的东西
12345 aaaaaaaaaabbbbbbbbbb
23456 bbcbcbbgyhuhuhhhhhhh
12345 7ijkunmmnniiiiiiii
23456 bbcbcbbgyhuhsdrfrrhhhv
我想基于第一个
将行合并为一行字段i,e。,
12345 aaaaaaaaaabbbbbbbbbb 12345 7ijkunmmnniiiiiiii
23456 bbcbcbbgyhuhuhhhhhhv 23456 bbcbcbbgyhuhsdrfrrhh
任何人都可以告诉我怎么做吗?
答案 0 :(得分:1)
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;
答案 1 :(得分:1)
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
答案 2 :(得分:1)
awk
替代方案:
awk '
{ A[$1] = A[$1] $0 " " }
END { for (k in A) print A[k] }' infile
将每一行连接到以$1
为键的关联数组。