有一组数据如下:
ID 1
1
2
3
4
ID 2
1
2
3
4
ID 3
1
2
3
4
想调整为如下:
ID 1
1,2,3,4
ID 2
1,2,3,4
ID 3
1,2,3,4
先看我写的代码,超复杂了:
#!/usr/bin/perl
use strict;
use warnings;
sub test {
open SOURCE, '<', "d:/code/abc.txt" or die $!;
open DEST, '>', "d:/code/def.txt" or die $!;
my $items = qq{};
while (<SOURCE>) {
if (/ID/){
if ($items) {
$items = join(' ', split(/n/, $items));
print DEST $items, "n";
$items = qq{};
}
print DEST $_; # include the last "n";
}
else {
$items .= $_
}
}
if ($items) {
$items = join(' ', split(/n/, $items));
print DEST $items, "n";
}
close SOURCE;
close DEST;
}
&test() ;
1;
再来看仙子的答案:
perl -lpe '$= /^ID|4$/ ? "n" : " " ' data.txt
一行就搞定了,这就是差距啊。