【问题标题】:Concatenate two columns and paste the merged column连接两列并粘贴合并的列
【发布时间】:2016-08-08 11:09:17
【问题描述】:

我有一个制表符分隔的文件,如下 -

 loci1  loci2   name1   name2
    utr3p   utr3p   TERF1   ISCA2
    utr3p   intron  LPP PAAF1
    utr3p   intron  RPL37A  RCC1
    coding  intron  BAG2    RP11
    intron  intron  KIF1B   SNORA21
    intron  downstream  GUSBP4  CTD
    intron  intron  CLTC    VMP1
    utr3p   utr3p   PCYT1A  ZHX3

我想连接两列 name1 和 name2(由“__”连接)。合并的列应作为新列“merged_names”粘贴到新文件中。我怎样才能使用 awk 来做到这一点。

预期输出 -

loci1   loci2   name1   name2   merged_names
utr3p   utr3p   TERF1   ISCA2   TERF1__ISCA2
utr3p   intron  LPP PAAF1   LPP__PAAF1
utr3p   intron  RPL37A  RCC1    RPL37A__RCC1
coding  intron  BAG2    RP11    BAG2__RP11
intron  intron  KIF1B   SNORA21 KIF1B__SNORA21
intron  downstream  GUSBP4  CTD GUSBP4__CTD
intron  intron  CLTC    VMP1    CLTC__VMP1
utr3p   utr3p   PCYT1A  ZHX3    PCYT1A__ZHX3

【问题讨论】:

  • 家庭作业?

标签: shell unix awk


【解决方案1】:
awk 'BEGIN{OFS="\t"; print "loci1  loci2   name1   name2 MERGED__NAMES"} {print $1,$2,$3,$4,$3 "__" $4}' infile
loci1  loci2   name1   name2 MERGED__NAMES
loci1   loci2   name1   name2   name1__name2
utr3p   utr3p   TERF1   ISCA2   TERF1__ISCA2
utr3p   intron  LPP     PAAF1   LPP__PAAF1
utr3p   intron  RPL37A  RCC1    RPL37A__RCC1
coding  intron  BAG2    RP11    BAG2__RP11
intron  intron  KIF1B   SNORA21 KIF1B__SNORA21
intron  downstream      GUSBP4  CTD     GUSBP4__CTD
intron  intron  CLTC    VMP1    CLTC__VMP1
utr3p   utr3p   PCYT1A  ZHX3    PCYT1A__ZHX3

【讨论】:

  • 我想知道您是否可以通过 print.++ 以某种方式避免那个长列表。您在打印时连接了字符串,值得在注释中提及。
【解决方案2】:

你可以使用这个awk:

awk 'BEGIN{OFS=FS="\t"} NR==1{$(NF+1)="merged_names"} NR!=1{$(NF+1)=$(NF-1) "__" $NF}1' file

更短的awk:

awk 'BEGIN{OFS=FS="\t"} {$(NF+1)=(NR==1)? "merged_names" : $(NF-1)"__"$NF}1' file

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多