我有这个代码:
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