加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

perl – 折叠具有多个字段的行

发布时间:2020-12-15 23:24:18 所属栏目:大数据 来源:网络整理
导读:我有这个代码: awk '!seen[$1,$2]++{a[$1]=(a[$1] ? a[$1]"," : "t") $2} END{for (i in a) print i a[i]} ' inputfile 我想要解决具有两个以上字段的行但总是以第一个字段为索引. 输入文件(三列制表符分隔): protein_1 membrane 1e-4protein_1 intracell
我有这个代码:

awk '!seen[$1,$2]++{a[$1]=(a[$1] ? a[$1]"," : "t") $2} END{for (i in a) print i a[i]} ' inputfile

我想要解决具有两个以上字段的行但总是以第一个字段为索引.

输入文件(三列制表符分隔):

protein_1   membrane    1e-4
protein_1   intracellular   1e-5
protein_2   membrane    1e-50
protein_2   citosol 1e-40

期望的输出(三列制表符分隔):

protein_1   membrane,intracellular 1e-4,1e-5
protein_2   membrane,citosol   1e-50,1e-40

谢谢!

在这里堆叠:

awk '!seen[$1,$2]++{a[$1]=(a[$1] ? a[$1]"t" : "t") $2};{a[$1]=(a[$1] ? a[$1]"," : "t") $3} END{for (i in a) print i a[i]} ' 1 inputfile

解决方法

我真的希望有人发布一些awk魔法,但我会继续现在抛弃更长形式的perl脚本:

use strict;
use warnings;

my @cols = ();
my $lastprotein = '';

while (<DATA>) {
    chomp;
    my ($protein,@data) = split "t";

    if ($protein ne $lastprotein && @cols) {
        print join("t",$lastprotein,map {join ',',@$_} @cols),"n";
        @cols = ();
    }

    push @{$cols[$_]},$data[$_] for (0..$#data);
    $lastprotein = $protein;
}

print join("t","n";

__DATA__
protein_1   membrane    1e-4
protein_1   intracellular   1e-5
protein_2   membrane    1e-50
protein_2   citosol 1e-40

输出

protein_1       membrane,1e-5
protein_2       membrane,citosol       1e-50,1e-40

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读