首页 > 解决方案 > 使用模式从文件中检索数据并使用文件名对其进行注释

问题描述

我有一个文件,bin.001.fasta看起来像这样:

>contig_655
GGCGGTTATTTAGTATCTGCCACTCAGCCTCGCTATTATGCGAAATTTGAGGGCAGGAGGAAACCATGAC
AGTAGTCAAGTGCGACAAGC
>contig_866
CCCAGACCTTTCAGTTGTTGGGTGGGGTGGGTGCTGACCGCTGGTGAGGGCTCGACGGCGCCCATCCTGG
CTAGTTGAAC
...

我想做的是获取一个新文件,其中第一列是检索 contig ID,第二列是没有的文件名.fasta

contig_655    bin.001
contig_866    bin.001

任何想法如何制作它?

标签: bash

解决方案


请您尝试以下操作。

awk -F'>' '
FNR==1{
  split(FILENAME,array,".")
  file=array[1]"."array[2]
}
/^>/{
  print $2,file
}
'  Input_file

或者,如果您的 Input_file 有超过 2 个点,则更通用,然后运行以下。

awk -F'>' '
FNR==1{
  match(FILENAME,/.*\./)
  file=substr(FILENAME,RSTART,RLENGTH-1)
}
/^>/{
  print $2,file
}
'  Input_file

说明:为上述代码添加详细说明。

awk -F'>' '                   ##Starting awk program from here and setting field separator as > here for all lines.
FNR==1{                       ##Checking condition if this is first line then do following.
  split(FILENAME,array,".")   ##Splitting filename which is passed to this awk program into an array named array with delimiter .
  file=array[1]"."array[2]    ##Creating variable file whose value is 1st and 2nd element of array with DOT in between as per OP shown sample.
}
/^>/{                         ##Checking condition if a line starts with > then do following.
  print $2,file               ##Printing 2nd field and variable file value here.
}
' Input_file                  ##Mentioning Input_file name here.

推荐阅读