查找与另一个文件匹配的行并将它们存储在单独的文件中

查找与另一个文件匹配的行并将它们存储在单独的文件中

我的人口档案看起来像这样

pop.file
HG1W
HG2W
HG3W
HG4W
...

另一个文件包含个人 ID(每个个人有 2 行,R1 和 R2)。

ind.file
HI.2613.007.Index_18.ED17_HG1W26-7_353_R1.fastq.gz
HI.2613.007.Index_18.ED17_HG1W26-7_353_R2.fastq.gz
HI.2613.007.Index_14.ED14_HG1W35-2_310_R1.fastq.gz
HI.2613.007.Index_14.ED14_HG1W35-2_310_R2.fastq.gz
HI.2622.001.Index_16.ED16_HG2W9-3_342_R1.fastq.gz
HI.2622.001.Index_16.ED16_HG2W9-3_342_R2.fastq.gz
HI.2613.007.Index_1.ED1_HG2W12-3_33_R1.fastq.gz
HI.2613.007.Index_1.ED1_HG2W12-3_33_R2.fastq.gz
...

我想将每个群体中的个体存储在一个单独的文件中,并获取像这样的输出文件

head HG1.population
HI.2613.007.Index_18.ED17_HG1W26-7_353_R1.fastq.gz
HI.2613.007.Index_18.ED17_HG1W26-7_353_R2.fastq.gz
HI.2613.007.Index_14.ED14_HG1W35-2_310_R1.fastq.gz
HI.2613.007.Index_14.ED14_HG1W35-2_310_R2.fastq.gz


head HG2.population
HI.2622.001.Index_16.ED16_HG2W9-3_342_R1.fastq.gz
HI.2622.001.Index_16.ED16_HG2W9-3_342_R2.fastq.gz
HI.2613.007.Index_1.ED1_HG2W12-3_33_R1.fastq.gz
HI.2613.007.Index_1.ED1_HG2W12-3_33_R2.fastq.gz

答案1

awk

awk -F_ '
  NR==FNR {ind[substr($1,1,3)]++} 
  {i = substr($3,1,3); f = i ".population"} 
  i in ind {print >> f; close(f)}
' pop.file ind.file

然后

$ head HG*
==> HG1.population <==
HI.2613.007.Index_18.ED17_HG1W26-7_353_R1.fastq.gz
HI.2613.007.Index_18.ED17_HG1W26-7_353_R2.fastq.gz
HI.2613.007.Index_14.ED14_HG1W35-2_310_R1.fastq.gz
HI.2613.007.Index_14.ED14_HG1W35-2_310_R2.fastq.gz

==> HG2.population <==
HI.2622.001.Index_16.ED16_HG2W9-3_342_R1.fastq.gz
HI.2622.001.Index_16.ED16_HG2W9-3_342_R2.fastq.gz
HI.2613.007.Index_1.ED1_HG2W12-3_33_R1.fastq.gz
HI.2613.007.Index_1.ED1_HG2W12-3_33_R2.fastq.gz

答案2

尝试这个,

for i in `cat pop.file | cut -c -3`
do
    grep $i ind.file > $i.population
done

相关内容