所以,我有一个这样的文件:
file1
:三列SNP Id Geno 1 a AB 2 a AB 3 a BB . . . . . . . . . 1 b AB 2 b BB 3 b AB . . . . . . . . . 1 c AA 2 c AB 3 c AA . . . . . . . . .
我需要一个这样的文件:
file2
:与带有基因型的 ID 数量一样多的列SNP Genoa Genob Genoc . . . 1 AB AB AA 2 AB BB AB 3 BB AB AA . . . . . . . . . . . .
答案1
该脚本既不简洁也不可读,但它可以工作,并且与已经发布的解决方案相反,awk
它还生成标题行:
sed 'G;s/^SNP.*/SNP/
/^1 /s/ \([^ ]*\) .*SNP[^[:cntrl:]]*/& Geno\1/
s/^\([0-9]*\) [^ ]*\( [AB]*\)\n\(.*\n\1 [AB ]*\)/\3\2/
s/^\([0-9]*\) [^ ]*\( [AB]*\)\(\n\)\(.*\)/\4\3\1\2/
h
$!d' file1 > file2
如果不是用户,awk
我想您也可以awk
像这样扩展给定的解决方案来生成标题行:
awk '{if ($1==1) h=h" Geno"$2
if ($1!="SNP") g[$1]=g[$1]" "$3}
END {print "SNP"h; for (i in g) print i g[i]}' file1 > file2
答案2
awk '{g[$1] = g[$1] " " $3}
END {for (i in g) print i g[i]}' < file1 > file2
或者保留顺序:
awk '! ($1 in g) {snp[n++] = $1}
{g[$1] = g[$1] " " $3}
END {for (i = 0; i < n; i++) print snp[i] g[snp[i]]}' < file1 > file2
要包含“SNP Genoa Genob...”标头:
awk 'NR == 1 {header = $1; prefix = $3; next}
first == "" {first = "" $1}
$1 == first {header = header " " prefix $2}
! ($1 in g) {snp[n++] = $1}
{g[$1] = g[$1] " " $3}
END {
print header
for (i = 0; i < n; i++) print snp[i] g[snp[i]]
}' < file1 > file2
答案3
perl -lane '
next if $. == 1; # skip header
$A[@A] = $F[1] if /^1\h/; # populate new header
push @{$h{$F[0]}}, $F[2]}{$,="\t"; # OFS = tab
print q/SNP/, map { "Geno$_" } @A; # new header print
print $_, @{$h{$_}} for sort { $a <=> $b } keys %h; # result
' gene.data
这里将第三个字段存储$F[2]
到 AoA (array_of_array) 中。最后,我们对哈希键进行数字排序,并打印数据。
sed -e '
1d; # monospace lines
s/[[:blank:]]\{1,\}/\t/g;s/^[[:blank:]]*//;s/[[:blank:]]*$//
H;g
# 1 2 3 4
s/\(\n\(.*\n\)\{0,1\}\)1[[:blank:]]\([^[:space:]]\{1,\}\)\([[:blank:]][^[:space:]]\{1,\}\)$/\tGeno\3\1\n1\4/
/\(\n[^[:space:]]\{1,\}[[:blank:]]\)[^[:space:]]\{1,\}[[:blank:]]\([^[:space:]]\{1,\}\)$/s//\1\2/
y/\n_/_\n/
s/_\([0-9]\{1,\}\)\([^_]*\)_\(.*_\)\{0,1\}\1\([[:blank:]][^_]*\)/_\1\2\4_\3/
y/\n_/_\n/
h;$!d
s/\n*$//
s/\n\(\n\)/\1/
s/^[[:blank:]]/SNP&/
' gene.data
结果
SNP Genoa Genob Genoc
1 AB AB AA
2 AB BB AB
3 BB AB AA