-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreconcile_fastq_to_fasta
executable file
·97 lines (82 loc) · 2.2 KB
/
reconcile_fastq_to_fasta
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#!/usr/bin/perl
# This script reads a fastq file and a fasta file
# and outputs the fastq records that have corresponding
# fasta entires.
#
# It assumes that the fasta records are a subset of the
# fastq records
#
# Mark Stenglein, June 15, 2011
use strict;
my $usage=<<USAGE;
This script reads a fastq file and a fasta file
and outputs the fastq records that have corresponding
fasta entires to standard output.
usage: reconcile_fastq_to_fasta <fastq_file> <fasta_file>
USAGE
if (scalar @ARGV == 0) { print $usage and exit; }
my $fastq_fn = shift or print $usage or warn "error: missing required argument: fastq file\n$usage" and exit;
my $fasta_fn = shift or print $usage or warn "error: missing required argument: fasta file\n$usage" and exit;
open (my $fastq_fh, "<", $fastq_fn) or warn "error: couldn't open fastq file: $fastq_fn\n$usage" and exit;
open (my $fasta_fh, "<", $fasta_fn) or warn "error: couldn't open fasta file: $fasta_fn\n$usage" and exit;
my %fasta_headers = ();
#TODO - make this configurable
my $split_ids = 1;
# First, parse fasta file and stick all headers in a hash
while (<$fasta_fh>)
{
chomp;
if (/^>/)
{
my $fasta_header = $_;
$fasta_header =~ s/>//;
if ($split_ids)
{
# only take part before 1st whitespace
if ($fasta_header =~ /(\S+)\s/)
{
$fasta_header = $1;
}
}
$fasta_headers{$fasta_header} = 1;
}
}
# next, parse fastq file and output records if found
# in corresponding fasta file
my $printing_lines = 0;
my $line_counter = 0;
while (<$fastq_fh>)
{
chomp;
$line_counter++;
if ($line_counter == 1)
{
if (!/^@/)
{
die ("error - was expecting 4-line fastq format. line: $_\n");
}
$printing_lines = 0;
my $fastq_header = $_;
$fastq_header =~ s/@//;
if ($split_ids)
{
# only take part before 1st whitespace
if ($fastq_header =~ /(\S+)\s/)
{
$fastq_header = $1;
}
}
if ($fasta_headers{$fastq_header})
{
$printing_lines = 1;
}
}
elsif ($line_counter == 4)
{
$line_counter = 0;
}
if ($printing_lines)
{
print "$_\n";
}
}