For a slightly more heavy-weight solution, if this fits in to the Bioconductor work flow,
source("http://bioconductor.org/biocLite.R")
biocLite("Rsamtools")
to install the Biostrings and Rsamtools package, then
library(Rsamtools)
indexFa("foo.fasta") # create an index of file 'foo.fasta'
fa = FaFile("foo.fasta") # reference the fasta file and it's index
You can discover the coordinates (names and start / end) of each sequence with
gr = as(seqinfo(fa), "GRanges")
and query for arbitrary sequences and ranges within sequences by choosing appropriate subsets, e.g., the second sequence and then first sequence in your example
getSeq(fa, gr[2:1])
or by looking up the coordinates by partial match to the names
idx = pmatch("gi|296783888", names(gr)) ## NA's if duplicates or not unique
seq = getSeq(fa, gr[idx])
"seq" is a DNAStringSet, and can be manipulated in many ways; see the vignettes available in the package
vignette(package="Biostrings")
especially the Quick Overview. To save the object to a fasta file 'file.fa' in a directory 'some' relative to the current working directory, use
writeXStringSet(seq, "some/file.fa")