Extract FASTA sequences based on sequence length using Perl

1 min read
extact fasta sequences using perl

Here are simple Perl scripts to filter out FASTA sequences from a multi-fasta file based on sequence length.

Let’s say our input file consisting of multiple FASTA sequences is ‘input.fasta’.
#!/usr/bin/perl
use strict;
use warnings;
my ($infile, $minlen) = @ARGV;
{
local $/=">";
while(<$infile>) {
chomp;
next unless /\w/;
my @keep = split /\n/;
my $header = shift @keep;
my $seqlen = length join "", @keep;
if($seqlen >= $minlen){
print ">$_";
}
}
local $/="\n";
}
exit;

Save this Perl script as ‘extractfasta.pl‘ and run in the terminal as

$ perl extractfasta.pl input.fasta <minlen> > output.fasta

For example,

$ perl extractfasta.pl input.fasta 100 > output.fasta

If you want to set a maximum length limit as well, then use the following script.
#!/usr/bin/perl
use strict;
use warnings;
my ($infile, $minlen, $maxlen) = @ARGV;
{
local $/=">";
while(<$infile>) {
chomp;
next unless /\w/;
my @keep = split /\n/;
my $header = shift @keep;
my $seqlen = length join "", @keep;
if($seqlen >= $minlen){
print ">$_";
}
}
local $/="\n";
}
exit;

Save this Perl script as ‘extractfasta.pl‘ and run in the terminal as

$ perl extractfasta.pl input.fasta <minlen> <maxlen> > output.fasta

For example,

$ perl extractfasta.pl input.fasta 100 350 > output.fasta

Muniba is a Bioinformatician based in the South China University of Technology. She has cutting edge knowledge of bioinformatics tools, algorithms, and drug designing. When she is not reading she is found enjoying with the family. Know more about Muniba

Leave a Reply

openbabel
Previous Story

Converting smiles into 3D structures using openbabel.

This month in Bioinformatics
Next Story

This month in Bioinformatics: Research Updates of July 2020

Latest from Bioinformatics Programming

0 $0.00