如何将备用行合并到每个后续列?

时间:2017-10-16 18:21:52

标签: bash awk sed merge newline

我尝试合并每列的替代行

输入:

ind1 T G T
     T T T 
ind2 G G T 
     G T T

所需的输出:

ind1 TT GT TT
ind2 GG GT TT

我尝试了这些命令:

sed 'N;s/\n/ /' <input> output 

paste - - <input> output

但它只合并备用线但添加整行,而不考虑列; e.g:

ind1 T G T T T T

ind2 G G T G T T

使用bash或python的想法吗?

3 个答案:

答案 0 :(得分:3)

awk救援!

$ awk 'NR%2 {n=split($0,a); next} 
            {for(i=1;i<n;i++) $i=a[i+1] $i; 
             print a[1],$0}' file

ind1 TT GT TT
ind2 GG GT TT

解释将奇数行拆分为列。合并下一行并打印。偶数行有一个字段,相应地移位和打印。

答案 1 :(得分:2)

非awk解决方案,因为你在bash或python中要求答案:

cut -f 1-4 -d ' ' in   | # the delimiter is a tab here
  sed 's/^/>/'         | # replace the start of the line with a >
    while read a b c d   # read the fields
    do if [[ "$a" = '>' ]]                     # if > then a second line
       then printf "$A\t$B$b\t$C$c\t$D$d\t\n"  # so stack them
       else A=${a#'>'}; B=$b; C=$c; D=$d;      # else set for stack later
       fi
    done

如果你想快速获取大量数据,我会使用perl。 或者是python。

或C.我讨厌awk。没有敲它的能力 - 我只是不喜欢它。

答案 2 :(得分:1)

GNU awk 解决方案(针对您当前的输入):

awk -F'\t' -v FPAT='[^[:space:]]+' 'NF>3{ h=$1; for(i=1;i<=3;i++) a[i]=$(i+1) }
              NF==3{ print h,a[1]$1,a[2]$2,a[3]$3 }' OFS='\t' file

输出:

ind1    TT  GT  TT
ind2    GG  GT  TT