<p><code>bedtools getfasta</code> can do this. See <a href="https://bedtools.readthedocs.io/en/latest/content/tools/getfasta.html" rel="noreferrer">documentation</a>. </p>

CC BY-SA 4.0
2018-11-05T15:49:16.650Z
2018-11-05T15:49:16.650Z
vkkodali
<p>UCSC 'kent' command line tool:</p>

<pre><code>faToTwoBit -bed=yourCoordinates.bed genomeSequence.2bit output.fa
</code></pre>

<p>Binary for this command and others available at: <a href="http://hgdownload.soe.ucsc.edu/admin/exe/linux.x86_64/" rel="nofollow noreferrer">UCSC kent command line tools</a></p>

CC BY-SA 4.0
2019-03-10T10:43:44.597Z
I think you mean `twoBitToFa`. Thanks anyway for pointing me in that direction.
Niklas Mertsch
CC BY-SA 4.0
2018-11-08T18:46:44.320Z
2018-11-08T18:46:44.320Z
Null Model
<p>You could start with a folder of <code>samtools faidx</code>-indexed FASTA files for your genome of interest:</p>

<pre><code><span class="math-container">$ mkdir /genomes/hg38 &amp;&amp; cd /genomes/hg38
$</span> wget ftp://hgdownload.cse.ucsc.edu/goldenPath/hg38/chromosomes/*.fa.gz
<span class="math-container">$ for fn in `ls *.fa.gz`; do gunzip $</span>fn; done
<span class="math-container">$ for fn in `ls *.fa`; do samtools faidx $</span>fn; done
</code></pre>

<p>Then use that folder with the following script:</p>

<pre><code>#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long;

#
# bed2faidxsta.pl
# --
# Reads BED data from standard input, writes FASTA to standard output.
#
# Dependent on samtools and indexed FASTA data files located in $fastaDir 
# variable. Set --fastaDir=dir to set custom directory containing a source 
# of per-build, bgzip-compressed FASTA and associated index (fa.gz.fai) 
# files, or leave unset to use data in current working directory. Use the
# --fastaIsUncompressed option if the FASTA files are not compressed.
#

# test if samtools is available
`samtools --version` || die "Error: The samtools application is required to run this script. Try 'module add samtools' or install a local copy of samtools.\n";

# default FASTA input is current working directory
my <span class="math-container">$fastaDir = `pwd`; chomp $</span>fastaDir;
# default is to assume input coordinates use zero-based index scheme
my <span class="math-container">$oneBased;
# default is to leave IDs alone
my $</span>useIDPrefixAsStrand;
# default is to assume FASTA files are bgzip-compressed
my $fastaIsUncompressed;

GetOptions ('fastaDir=s' =&gt; \$fastaDir, 'oneBased' =&gt; \$oneBased, 'useIDPrefixAsStrand' =&gt; \$useIDPrefixAsStrand, 'fastaIsUncompressed' =&gt; \$fastaIsUncompressed);

if (! -d $fastaDir) { die "Error: FASTA directory does not exist\n"; }

while (&lt;STDIN&gt;) {
    chomp;
    my (<span class="math-container">$chr, $</span>start, <span class="math-container">$stop, $</span>id, <span class="math-container">$score, $</span>strand) = split("\t", <span class="math-container">$_);
if (!defined($</span>chr) || !defined(<span class="math-container">$start) || !defined($</span>stop)) { die "Error: No chromosome name, start or stop position defined\n"; }
    if (!defined(<span class="math-container">$id)) { $id = "."; }
if (!defined($</span>score)) { <span class="math-container">$score = "."; }
if (!defined($</span>strand)) { <span class="math-container">$strand = "+"; } else { $strand = substr($strand, 0, 1); }
# adjust coordinates to one-based index, if necessary
my ($</span>queryChr, <span class="math-container">$queryStart, $</span>queryStop) = (<span class="math-container">$chr, $</span>start, <span class="math-container">$stop);
if (!$</span>oneBased) {
        <span class="math-container">$queryStart++;
}
# adjust strand if required
if ($</span>useIDPrefixAsStrand) {
        <span class="math-container">$strand = substr($</span>id, 0, 1);
    }
    # lookup
    my <span class="math-container">$queryFn = "$</span>fastaDir/<span class="math-container">$chr.fa.gz";
if ($</span>fastaIsUncompressed) {
        <span class="math-container">$queryFn = "$</span>fastaDir/<span class="math-container">$chr.fa";
}
my $</span>queryKey = "<span class="math-container">$queryChr:$</span>queryStart-<span class="math-container">$queryStop";
my $</span>queryResult = `samtools faidx $queryFn $queryKey`; chomp <span class="math-container">$queryResult; 
# linearize result
my @lines = split("\n", $</span>queryResult);
    my @seqs = @lines[1..(scalar @lines - 1)];
    my <span class="math-container">$seq = join("", @seqs);
# handle reverse-stranded elements
if ($</span>strand eq "-") {
        <span class="math-container">$seq = rc_sequence($</span>seq);
    }
    # print to standard output
    my <span class="math-container">$header = "&gt;".join(":",($</span>chr, <span class="math-container">$start, $</span>stop, <span class="math-container">$id, $</span>score, <span class="math-container">$strand));
print STDOUT $</span>header."\n".$seq."\n";
}

sub rc_sequence {
    my <span class="math-container">$seq = shift @_;
my $</span>reverse_complement = reverse(<span class="math-container">$seq);
$</span>reverse_complement =~ tr/ACGTacgt/TGCAtgca/;
    return $reverse_complement;
}
</code></pre>

<p>Then:</p>

<pre><code>$ perl bed2faidxsta.pl &lt; in.bed &gt; out.fa
</code></pre>

<p>This approach can be useful with stranded input, nonstandard genomes, or just to do things with a bit more knowledge of inputs.</p>

CC BY-SA 4.0
2018-11-05T18:37:36.093Z
Or, since you already have samtools, the poster can use samtools faidx with a file of regions.  It won't be hard to get a bedfile into the right format: http://www.htslib.org/doc/samtools.html
swbarnes2
CC BY-SA 4.0
2018-11-05T16:21:45.753Z
2018-11-05T16:21:45.753Z
Alex Reynolds
<p>I have Bed file containing start and end of a sequence, and I need to convert it to fasta format, any recommendations?</p>

CC BY-SA 4.0
2018-11-05T11:28:54.643Z
Please [edit] your question and give us more details. Bed files define regions, do you have a fasta file of the target regions? Is this for a genome? Do you have that genome?
terdon
<file-formats>
How to convert Bed file to fasta file?
# How to convert Bed file to fasta file?

(Asked by: username_0 on 2018-11-05)

I have Bed file containing start and end of a sequence, and I need to convert it to fasta format, any recommendations?

**Tags:** file-formats
> **Comments:**
> **username_1**: Please [edit] your question and give us more details. Bed files define regions, do you have a fasta file of the target regions? Is this for a genome? Do you have that genome?  

---

## 3 answers

### Answer by username_2 on 2018-11-05. Score: 5

`bedtools getfasta` can do this. See [documentation](https://bedtools.readthedocs.io/en/latest/content/tools/getfasta.html).


---

### Answer by username_3 on 2018-11-08. Score: 1

UCSC 'kent' command line tool:
faToTwoBit -bed=yourCoordinates.bed genomeSequence.2bit output.fa

Binary for this command and others available at: UCSC kent command line tools

> **Comments:**
> **username_4**: I think you mean `twoBitToFa`. Thanks anyway for pointing me in that direction.  

---

### Answer by username_5 on 2018-11-05. Score: 1

You could start with a folder of samtools faidx-indexed FASTA files for your genome of interest:
$ mkdir /genomes/hg38 && cd /genomes/hg38
$ wget ftp://hgdownload.cse.ucsc.edu/goldenPath/hg38/chromosomes/*.fa.gz
$ for fn in `ls *.fa.gz`; do gunzip $fn; done
$ for fn in `ls *.fa`; do samtools faidx $fn; done

Then use that folder with the following script:
#!/usr/bin/env perl

use strict;
use warnings;
use Getopt::Long;

#
# bed2faidxsta.pl
# --
# Reads BED data from standard input, writes FASTA to standard output.
#
# Dependent on samtools and indexed FASTA data files located in $fastaDir 
# variable. Set --fastaDir=dir to set custom directory containing a source 
# of per-build, bgzip-compressed FASTA and associated index (fa.gz.fai) 
# files, or leave unset to use data in current working directory. Use the
# --fastaIsUncompressed option if the FASTA files are not compressed.
#

# test if samtools is available
`samtools --version` || die "Error: The samtools application is required to run this script. Try 'module add samtools' or install a local copy of samtools.\n";

# default FASTA input is current working directory
my $fastaDir = `pwd`; chomp $fastaDir;
# default is to assume input coordinates use zero-based index scheme
my $oneBased;
# default is to leave IDs alone
my $useIDPrefixAsStrand;
# default is to assume FASTA files are bgzip-compressed
my $fastaIsUncompressed;

GetOptions ('fastaDir=s' => \$fastaDir, 'oneBased' => \$oneBased, 'useIDPrefixAsStrand' => \$useIDPrefixAsStrand, 'fastaIsUncompressed' => \$fastaIsUncompressed);

if (! -d $fastaDir) { die "Error: FASTA directory does not exist\n"; }

while () {
    chomp;
    my ($chr, $start, $stop, $id, $score, $strand) = split("\t", $_);
if (!defined($chr) || !defined($start) || !defined($stop)) { die "Error: No chromosome name, start or stop position defined\n"; }
    if (!defined($id)) { $id = "."; }
if (!defined($score)) { $score = "."; }
if (!defined($strand)) { $strand = "+"; } else { $strand = substr($strand, 0, 1); }
# adjust coordinates to one-based index, if necessary
my ($queryChr, $queryStart, $queryStop) = ($chr, $start, $stop);
if (!$oneBased) {
        $queryStart++;
}
# adjust strand if required
if ($useIDPrefixAsStrand) {
        $strand = substr($id, 0, 1);
    }
    # lookup
    my $queryFn = "$fastaDir/$chr.fa.gz";
if ($fastaIsUncompressed) {
        $queryFn = "$fastaDir/$chr.fa";
}
my $queryKey = "$queryChr:$queryStart-$queryStop";
my $queryResult = `samtools faidx $queryFn $queryKey`; chomp $queryResult; 
# linearize result
my @lines = split("\n", $queryResult);
    my @seqs = @lines[1..(scalar @lines - 1)];
    my $seq = join("", @seqs);
# handle reverse-stranded elements
if ($strand eq "-") {
        $seq = rc_sequence($seq);
    }
    # print to standard output
    my $header = ">".join(":",($chr, $start, $stop, $id, $score, $strand));
print STDOUT $header."\n".$seq."\n";
}

sub rc_sequence {
    my $seq = shift @_;
my $reverse_complement = reverse($seq);
$reverse_complement =~ tr/ACGTacgt/TGCAtgca/;
    return $reverse_complement;
}

Then:
$ perl bed2faidxsta.pl < in.bed > out.fa

This approach can be useful with stranded input, nonstandard genomes, or just to do things with a bit more knowledge of inputs.

> **Comments:**
> **username_6**: Or, since you already have samtools, the poster can use samtools faidx with a file of regions.  It won't be hard to get a bedfile into the right format: http://www.htslib.org/doc/samtools.html  

---

