Count Sequences in a FASTA Stream

Foundational Bash Foundations Bash grep Counting FASTA
Significance:

Counting records in a FASTA file is the single most common one-liner in
bioinformatics — you run it to sanity-check a download, to verify a filter did what you expected, and to
report dataset sizes in a methods section. It also teaches the core Unix insight that you rarely need to
write a program when a text-processing tool already does the job.

Statement

FASTA-formatted text arrives on standard input. Every record begins with a header line
whose first character is >.

Print a single integer: the number of records in the stream.

Lines that merely contain a > somewhere other than the first character are sequence lines, not
headers, and must not be counted.

Input — read from standard input
Variable Type Description
fasta
line 1..n
str FASTA-formatted text on standard input
0 <= records <= 1000

These variables are already read for you in the starter code on the right.

Output

str a single integer, the number of FASTA records

Sample Cases
Sample 1
Input
>seq1
ACGT
>seq2
TTTT
>seq3
GGGG
Expected Output
3
Three header lines, so three records.
Sample 2
Input
>only
ACGTACGT
Expected Output
1
A single record.

Submit also runs your code against 3 hidden test cases. Hidden inputs are never shown — if one fails you'll get its number and a description of the mismatch, not the data.

Constraints
  • Only lines whose first character is > count as headers
  • The stream may be empty, in which case the answer is 0
  • Blank lines are ignored
  • Solutions must read standard input and write to standard output only
Further Reading
  • grep -c counts matching lines rather than printing them.
  • Anchor the pattern to the start of the line with ^ so mid-line > characters are not matched.
  • grep -c exits with status 1 when nothing matches, which can abort a script running under set -e.

Judged against GNU Bash 5.1.0.


My Notes
Log in to save personal notes.
Console output will appear here when you click Run Code or Submit...
Expected: fasta — the whole input (FASTA-formatted text on standard input)
Next Problem
Extract FASTA Identifiers