3  Reading genomic files

Your collaborator sends you a file called peaks.bed and asks how many peaks fall on chromosome 22. Before you run any tool, look at the file. Does it have a header? Tabs between the columns? Is it compressed? Does it say chr22 or 22? Does it count from 0 or from 1? Get one wrong and your answer is quietly wrong, with no error message. A two-second look answers them all. Look before you analyze.

When I started, a 2 GB text file defeated me because Excel couldn’t open it. The commands in this lesson open a file of any size in a blink, because they read only the part you ask for.

This lesson stands on its own. Every command has a ▶ Run button that runs it in a real Linux terminal at the bottom of the page, with the files already in data/: nothing to install (though typing the commands yourself is better). New to the terminal? Lessons 1 and 2 cover the basics, and the Welcome page shows how to set up your own copy.

In this lesson you’ll learn

Every file is real: human chromosome 22, reads from Richard Lenski’s evolving E. coli, the binding sites of the DNA-looping protein CTCF, and the variants of NA12878, one of the most studied people in the world, and her parents.

3.1 Look before you analyze

Start with the people. cat prints a whole file, which is fine for a small one:

cat data/variants/samples.tsv
sample  sex population  superpopulation father  mother
NA18486 male    YRI AFR .   .
NA18487 male    YRI AFR .   .
NA18488 female  YRI AFR .   .
NA18489 female  YRI AFR .   .
HG01565 male    PEL AMR .   .
HG01566 female  PEL AMR .   .
HG01571 male    PEL AMR .   .
NA18525 female  CHB EAS .   .
NA18526 female  CHB EAS .   .
NA18528 female  CHB EAS .   .
NA18530 male    CHB EAS .   .
NA12878 female  CEU EUR NA12891 NA12892
NA12891 male    CEU EUR .   .
NA12892 female  CEU EUR .   .
HG00096 male    GBR EUR .   .
HG00097 female  GBR EUR .   .
HG00099 female  GBR EUR .   .
NA20845 male    GIH SAS .   .
NA20846 male    GIH SAS .   .
NA20847 female  GIH SAS .   .

These are the 20 people in our variant files, from the 1000 Genomes Project, with their sex, population and super-population (YRI are Yoruba from Nigeria, CEU are Utah residents of European ancestry, GIH are Gujarati Indians from Houston, and so on). Now look at NA12878: her father is NA12891 and her mother is NA12892. She is the Genome in a Bottle reference sample, the genome that sequencing technologies are benchmarked against.

head shows the first lines of a file, tail the last ones, and -n says how many:

head -n 3 data/variants/samples.tsv
sample  sex population  superpopulation father  mother
NA18486 male    YRI AFR .   .
NA18487 male    YRI AFR .   .
tail -n 2 data/variants/samples.tsv
NA20846 male    GIH SAS .   .
NA20847 female  GIH SAS .   .

The first line is a header: column names, not data. To skip it, put a plus sign in front of the number. tail -n +2 means “start at line 2”:

tail -n +2 data/variants/samples.tsv | head -n 3
NA18486 male    YRI AFR .   .
NA18487 male    YRI AFR .   .
NA18488 female  YRI AFR .   .

The vertical bar | is a pipe: it sends the output of tail into head (lesson 6 is all about pipes).

cat -n numbers the lines, and head and tail together cut out any range. Lines 13 to 15 are the family:

cat -n data/variants/samples.tsv | head -n 15 | tail -n 3
    13  NA12878 female  CEU EUR NA12891 NA12892
    14  NA12891 male    CEU EUR .   .
    15  NA12892 female  CEU EUR .   .

For lines M to N, use head -n N | tail -n K, where K = N − M + 1: here 15 − 13 + 1 = 3. Forget the “+ 1” and you get one line too few: an off-by-one error, my vote for the most common mistake in bioinformatics. We’ll meet it again with BED files.

3.1.1 Scroll through a big file: less

less shows a file one screen at a time and loads only what you see, so even a 100 GB file opens instantly. -S stops long lines from wrapping:

less -S data/reads/NA12878.small.sam
Key What it does
Space or f Next page
b Previous page
↓ ↑ ← → Move by a line, or sideways along long lines (with -S)
/word then Enter Search for “word”; n jumps to the next match
g / G Go to the start / the end
q Quit

3.1.2 Count lines: wc

wc (word count) counts lines, words and bytes:

wc data/variants/samples.tsv
 21 126 586 data/variants/samples.tsv

21 lines, 126 words, 586 bytes. Usually you want only the lines: -l. Feed the file in with < and you get the bare number, handy in scripts:

wc -l data/variants/samples.tsv
wc -l < data/variants/samples.tsv
21 data/variants/samples.tsv
21

21 lines: one header plus 20 people. Always ask whether a count includes a header.

NoteFrom my blog

3.2 Compressed files: zcat, gzip and friends

Most genomics files end in .gz: compressed with gzip. Why? wc -c counts bytes, and zcat decompresses a file to the screen (here, straight into wc). Compare the chromosome 22 gene annotation on disk and as text:

wc -c data/annotation/gencode.v50.chr22.gtf.gz
zcat data/annotation/gencode.v50.chr22.gtf.gz | wc -c
3025251 data/annotation/gencode.v50.chr22.gtf.gz
115727517

3 MB on disk, 116 MB as text: 38 times smaller, because annotation text repeats the same words over and over. And you rarely need to unpack anything: zcat streams the text and leaves the file alone. Pipe it into head to peek:

zcat data/annotation/gencode.v50.chr22.gtf.gz | head -n 5
##description: evidence-based annotation of the human genome (GRCh38), version 50 (Ensembl 116)
##provider: GENCODE
##contact: gencode-help@ebi.ac.uk
##format: gtf
##date: 2026-04-08

gzip -dc does the same (-d decompress, -c to the screen). zless and zgrep are less and grep for compressed files. Linux and Macs have them, and they’re worth knowing, but the terminal on this page doesn’t. So the tour below pipes zcat into grep and less instead: zcat file.gz | grep 'pattern' prints exactly what zgrep 'pattern' file.gz prints.

If a program really needs the plain file, gunzip unpacks it. Work on a copy, and add -k to keep the .gz (without it, gunzip deletes it):

cp data/reads/SRR2589044_1.fastq.gz sample.fastq.gz
gunzip -k sample.fastq.gz
wc -c sample.fastq.gz sample.fastq
1195470 sample.fastq.gz
3653583 sample.fastq
4849053 total

Three times bigger unpacked. gzip compresses it again and replaces sample.fastq with sample.fastq.gz, so remove the old copy first:

rm sample.fastq.gz
gzip sample.fastq
ls
rm sample.fastq.gz
data
sample.fastq.gz
WarningGotcha: zcat on a Mac

The zcat built into macOS expects old .Z files. On a .gz file it fails with zcat: can't stat: file.gz (file.gz.Z): No such file or directory. Use gzip -dc file.gz instead, which works everywhere (on a Mac, gzcat file.gz works too), or install GNU gzip (brew install gzip), or use the Codespace.

A note for later: the .vcf.gz and .bam files here use bgzip, a gzip variant built in blocks so tools can jump to any position (lesson 10). zcat reads a .vcf.gz like any other .gz file.

3.3 See the invisible: tabs and line endings

A tab and a few spaces look the same on screen, but not to a program. cat -A shows all the invisible characters: a tab becomes ^I, and $ marks the end of each line (on a Mac the built-in cat has no -A; cat -vet shows the same ^I, ^M and $):

head -n 2 data/peaks/ctcf_gm12878.narrowPeak | cat -A
chr22^I36856375^I36856663^I.^I1000^I.^I317.01925^I-1.00000^I4.81020^I144$
chr22^I41666686^I41666949^I.^I1000^I.^I290.74265^I-1.00000^I4.81020^I134$

Tabs between the columns and nothing hiding at the ends: a clean file. Now a sample sheet saved from Excel on Windows (simulated for the course, but this is how such files arrive):

head -n 3 data/messy/sample_sheet_from_excel.csv | cat -A
M-oM-;M-?Sample ID,Population,Super population,Sex,Sequencing batch^M$
NA18486,YRI,AFR,Male,batch1^M$
NA18487,YRI,AFR,male,batch2^M$

Every line ends in ^M$: Windows ends lines with a carriage return (^M, or \r) plus a newline, where Linux uses only the newline. The M-oM-;M-? at the start is a byte-order mark, three invisible bytes Excel glues onto the first column name. So a program sees a last column called Sequencing batch\r, and code that asks for Sequencing batch finds nothing. Windows line endings have bitten me many times; lesson 8 cleans this file.

To read a table by eye, column -t lines up its columns. It’s for your eyes only; don’t save its output as data:

head -n 5 data/variants/samples.tsv | column -t
sample   sex     population  superpopulation  father  mother
NA18486  male    YRI         AFR              .       .
NA18487  male    YRI         AFR              .       .
NA18488  female  YRI         AFR              .       .
NA18489  female  YRI         AFR              .       .

cut -f keeps only the columns (fields) you list, splitting on tabs; -f 1-3 means fields 1 to 3:

cut -f 1-3 data/peaks/ctcf_gm12878.narrowPeak | head -n 3
chr22   36856375    36856663
chr22   41666686    41666949
chr22   39529282    39529538

cut -c 1-80 keeps the first 80 characters of each line instead. Lesson 5 covers cut properly; below, I use it to keep outputs readable.

3.4 FASTA: genomes and proteins

FASTA stores DNA or protein sequences. A line starting with > names a sequence; the lines after it, up to the next >, are the sequence.

head -n 3 data/genome/chr22.fa
>chr22
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
NNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN

This is human chromosome 22 from the GRCh38 reference genome. N means an unknown base: the short arm of chromosome 22 is a long stretch of repeats, including ribosomal RNA genes, that the reference could not assemble. The known sequence starts on line 210,202, after 10,510,000 N’s (I found that line with grep, the subject of lesson 4). A little further in:

tail -n +210211 data/genome/chr22.fa | head -n 3
tttacagtgtgccaagatcacaccaccctactccaacttgggtgacagag
caagactcagtctcaaggaaaaaaaaaaGCTCGAAAAATGTTTGCTTATT
TTGGTAAAATTATTCATTGACTATGCTCAGAAATCAAGCAAACTGTCCAT

Lowercase letters are repeats, such as transposable elements, flagged by programs like RepeatMasker. This soft-masking keeps every base and lets the case carry the extra information. Some tools ignore it, others treat lowercase specially.

How big is it?

wc -l data/genome/chr22.fa
cat data/genome/chr22.fa.fai
1016371 data/genome/chr22.fa
chr22   50818468    7   50  51

1,016,371 lines: a name line, then 50 letters per line. The .fai index, made by samtools faidx, stores the name, the length (50,818,468 bases), the byte where the sequence starts (7), the letters per line (50) and the bytes per line (51, with the newline). With it, tools jump straight to any position (lesson 10).

A protein FASTA holds one record per protein. The first two proteins of E. coli REL606, the ancestor of Lenski’s long-term evolution experiment (running since 1988):

head -n 4 data/ecoli/rel606_proteins.faa
>WP_000002107.1 MULTISPECIES: ASCH domain-containing protein [Enterobacteriaceae]
MANLQLAVKGEYFDAMIRGEKTEEYRLCNDYWNKRIMFREYDRLIITKGYPKRDDSSRRIDVPYDGYEIKTITHPHFGDK
PVKVFAIKVNIGNE
>WP_000002283.1 MULTISPECIES: alpha-D-ribose 1-methylphosphonate 5-phosphate C-P-lyase PhnJ [Enterobacteriaceae]

The letters are amino acids; each protein starts with M, methionine. Every record has one > line, so counting > lines counts proteins. grep finds lines that contain a pattern and -c counts them (lesson 4 is all about grep):

grep -c '>' data/ecoli/rel606_proteins.faa
4167

4,167 proteins.

WarningGotcha: always quote the >

Without quotes, grep -c > data/ecoli/rel606_proteins.faa means “run grep -c and save its output into rel606_proteins.faa”. The shell empties the file before grep even starts, and your protein file is gone. Quote the >, every time.

3.5 FASTQ: sequencing reads

FASTQ files hold the raw reads from a sequencer, with a quality score for every base. Ours come from three evolved E. coli samples from Lenski’s experiment, sequenced paired-end: each DNA fragment was read from both ends, so each sample has a _1 and a _2 file.

zcat data/reads/SRR2589044_1.fastq.gz | head -n 4
@SRR2589044.1 HWI-ST957:244:H73TDADXX:1:1101:10469:2228/1
GTGGAAACCAGCGACGGTGACGGCTATATCAACTGCGTGATTGAACATCAAAGCTCTGCAGAAAAGAATATGGCTTTTCGGCTAATGCGCTATGCCACTGCCGCCATGCAGCGTCACCTGGATAACTGTCTCTTATACACATCTCCGAGC
+
BBBFFFFFHHHHHJJJJIIGIIJJJJJGIJJIJJJIJIJGHIIJIIFFFGHHFFFFFEEEEEEDDDDDDDEEDCDDDDDD@BDDDDDDDDBDDDDDDDDDCABDDDDCDDCCDBDDDDDDDBDEDDDCCDCDCDDDDCDDDCDDDD@DDD

One read takes exactly four lines:

  1. @ and the read name: read 1 of run SRR2589044, then the instrument, run number, flowcell, lane, tile and x:y position of the DNA cluster (HWI-ST957:244:H73TDADXX:1:1101:10469:2228). /1 marks the first read of the pair.
  2. The sequence: 150 bases.
  3. A +, a separator.
  4. The quality: one character for each base.

Look at the end of the sequence: CTGTCTCTTATACACATCT is the Nextera library adapter, not E. coli DNA. The fragment was shorter than 150 bases, so the sequencer read through it into the adapter. Trimming tools remove it before alignment.

Each quality character is a number, the Phred score Q: its ASCII code minus 33. Q says how likely the base is wrong: Q20 is 1 in 100, Q30 is 1 in 1,000.

Character # 5 ? @ I J
Phred score Q 2 20 30 31 40 41
Chance the base is wrong 63% 1% 0.1% 0.08% 0.01% 0.008%

This read is mostly B to J (Q33 to Q41): very good. Now its mate, the other end of the same fragment:

zcat data/reads/SRR2589044_2.fastq.gz | head -n 4
@SRR2589044.1 HWI-ST957:244:H73TDADXX:1:1101:10469:2228/2
TTATCCAGGTGACGCTGCATGGCGNNNNNNNNATAGCGCATTAGCCNNNNNNNNATATTCTTTTCTGCANNNNNTTGATGTTCAATCACNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNNN
+
CCCFFFFFHFFHHJJIIIJJJJJJ########00?DHHIJJJGGIJ########-,;BDDDEEEEEDDD#####,,8?BDFDEEDDDCC#############################################################

Same name, ending in /2, but full of Ns with a # (Q2) under each: bases the sequencer could not call. Quality control tools catch reads like this.

To count reads, count lines and divide by 4:

zcat data/reads/SRR2589044_1.fastq.gz | wc -l
40000

40,000 lines, so 10,000 reads.

WarningGotcha: don’t count reads by counting @

Every read name starts with @, so why not count those lines? ^@ means “lines that start with @”:

zcat data/reads/SRR2589044_1.fastq.gz | grep -c '^@'
13450

13,450, for a file with 10,000 reads. The problem is that @ is also a quality character (Q31), and quality lines can start with it. Here are lines 5 to 8, the second read:

zcat data/reads/SRR2589044_1.fastq.gz | head -n 8 | tail -n 4
@SRR2589044.2 HWI-ST957:244:H73TDADXX:1:1101:10877:2125/1
GCAATATTACCGGGCGACATCGCCGAAGATGACATCACAGCGGTACTCTGTTTTGTGATTGAAGCCGATCAGATTACCTTTGAAACAGTAGAAGTCTCGCCAAAAATATCCACCCCACCAGTGCTTAAACTGGCAGCCGAACAAGCGCCA
+
@@CFDDFFDB>DHGEBEADGID;GEAFEFEHGEGCHGEGECHF'9=>CCCCCCCA5=ADCC@CCCBC>8B>CCCCCCCCCCCCCCCCC@@C>AACCC@?@B<BCBBACEDECCCBCBB@@B>CCECCCCAACCBCBBBB>9>BCA8<9<B

Its quality line starts with @@. Count lines and divide by 4.

3.6 BED and narrowPeak: genomic intervals

BED files store genome intervals: a chromosome, a start, an end, and optional extra columns. These are ENCODE CTCF ChIP-seq peaks, the places on chromosome 22 where CTCF binds DNA in GM12878 cells. GM12878 was made from NA12878’s own blood cells, so these peaks and her variants come from the same person.

head -n 3 data/peaks/ctcf_gm12878.narrowPeak
chr22   36856375    36856663    .   1000    .   317.01925   -1.00000    4.81020 144
chr22   41666686    41666949    .   1000    .   290.74265   -1.00000    4.81020 134
chr22   39529282    39529538    .   1000    .   264.14260   -1.00000    4.81020 126

narrowPeak is BED with 10 columns, the format that peak callers such as MACS2 write:

Column Name First peak Meaning
1 chrom chr22 Chromosome
2 chromStart 36856375 Start, counting from 0
3 chromEnd 36856663 End (not included)
4 name . Peak name (none here)
5 score 1000 0 to 1000, used by genome browsers to shade the peak
6 strand . No strand: binding is on double-stranded DNA
7 signalValue 317.01925 How strong the enrichment is
8 pValue -1.00000 −log10 p-value; −1 means not computed
9 qValue 4.81020 −log10 q-value (FDR)
10 peak 144 The summit, as an offset from chromStart
WarningGotcha: BED counts from 0

BED coordinates are 0-based, half-open: the start is counted from 0 and the end is not included. So the first peak is 36856663 − 36856375 = 288 bases wide, with no “+ 1”. In the 1-based counting that genome browsers display, it covers bases 36,856,376 to 36,856,663. GTF, GFF3, VCF and SAM count from 1 and include both ends. Mixing the two is the classic off-by-one error.

Count the peaks in all three files at once. The * matches every file name that ends in .narrowPeak (lesson 4 explains these wildcards):

wc -l data/peaks/*.narrowPeak
   789 data/peaks/ctcf_gm12878.narrowPeak
  1124 data/peaks/ctcf_k562.narrowPeak
   395 data/peaks/rad21_gm12878.narrowPeak
  2308 total

789 CTCF peaks in GM12878, 1,124 in K562 (a leukemia cell line), and 395 peaks of RAD21, part of cohesin. CTCF and cohesin fold DNA into loops together, so most RAD21 peaks sit on CTCF peaks (lesson 10 counts them). Notice too that the peaks are sorted by signal, not by position; many tools need sorted input (lesson 5).

NoteFrom my blog

3.7 GTF and GFF3: gene annotation

GTF files say where the genes, transcripts, exons and coding sequences are. Let’s find COMT, a 22q11.2 gene whose enzyme breaks down dopamine. zcat streams the file into grep (that’s all zgrep does), and -m 1 stops at the first match, which for a gene is its gene line:

zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "COMT";' | cut -f 1-8
chr22   HAVANA  gene    19941371    19969975    .   +   .

A GTF line has 9 tab-separated columns:

Column Name COMT Meaning
1 seqname chr22 Chromosome
2 source HAVANA Who annotated it (HAVANA is the manual annotation team)
3 feature gene gene, transcript, exon, CDS, UTR, start_codon…
4 start 19941371 Start, counting from 1
5 end 19969975 End, included
6 score . Not used here
7 strand + The gene reads left to right on this strand
8 frame . For CDS lines: 0, 1 or 2 bases to skip to reach the first full codon
9 attributes see below Everything else, as key "value"; pairs

Because GTF is 1-based and includes both ends, the length is end − start + 1: 19969975 − 19941371 + 1 = 28,605 bases. The ninth column is long, so here are its first 100 characters:

zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "COMT";' | cut -f 9 | cut -c 1-100
gene_id "ENSG00000093010.17"; gene_type "protein_coding"; gene_name "COMT"; level 1; hgnc_id "HGNC:2

The gene ID (ENSG00000093010.17, version after the dot), type and name. Every transcript, exon and CDS line of COMT carries the same gene_id; that’s how they connect. How many lines in total?

zcat data/annotation/gencode.v50.chr22.gtf.gz | wc -l
278854

278,854 lines for one chromosome, including the 5 ## header lines you saw earlier (later lessons count the genes, transcripts and exons). To scroll through it, pipe it into less -S (q quits; zless -S file.gz does the same where you have it):

zcat data/annotation/gencode.v50.chr22.gtf.gz | less -S

GFF3 is the same idea in a stricter dialect. Here is the start of Ensembl’s annotation:

zcat data/annotation/Homo_sapiens.GRCh38.116.chr22.gff3.gz | head -n 10 | cut -c 1-100
##gff-version 3
##sequence-region   22 1 50818468
#!genome-build Genome Reference Consortium GRCh38.p14
#!genome-version GRCh38
#!genome-date 2013-12
#!genome-build-accession GCA_000001405.29
#!genebuild-last-updated 2025-11
22  GRCh38  chromosome  1   50818468    .   .   .   ID=chromosome:22;Alias=CM000684.2,chr22,NC_000022.11
###
22  havana_tagene   ncRNA_gene  10524345    10529164    .   -   .   ID=gene:ENSG00000294541;biotype=lncRNA;descripti

The same 9 columns. Header lines start with ## or #!, ### lines separate groups of features, and column 9 holds key=value pairs, where ID and Parent link exons to transcripts and transcripts to genes. Now COMT again:

zcat data/annotation/Homo_sapiens.GRCh38.116.chr22.gff3.gz | grep -m 1 'Name=COMT;' | cut -f 1-8
22  ensembl_havana  gene    19941371    19969975    .   +   .

Same coordinates, but the first column says 22, not chr22.

WarningGotcha: chr22 or 22?

UCSC and GENCODE say chr22; Ensembl says 22; NCBI files often use the accession NC_000022.11 (all three appear in the Alias of the GFF3’s chromosome line above). Compare a chr22 file with a 22 file and a tool finds nothing in common, with no error. Check the first column of every file before combining them; lesson 10 shows how to rename chromosomes safely.

3.8 VCF: variants

VCF files hold genetic variants: where a person’s DNA differs from the reference. Our big VCF covers chromosome 22 from 19 to 21 million bases, the 22q11.2 region, whose deletion causes 22q11.2 deletion (DiGeorge) syndrome, the most common microdeletion in people, in about 1 in 4,000 births. A VCF starts with meta-information lines beginning with ##:

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 4
##fileformat=VCFv4.2
##FILTER=<ID=PASS,Description="All filters passed">
##fileDate=29/01/2022 - 14:31:41
##source=shapeit4.2.2

Count them with grep -c and the pattern ^##, “lines that start with ##”:

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | grep -c '^##'
41

41 meta lines, so line 42 is the header line, which starts with a single #. Here are its first 12 columns:

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 42 | tail -n 1 | cut -f 1-12
#CHROM  POS ID  REF ALT QUAL    FILTER  INFO    FORMAT  NA18486 NA18487 NA18488

Eight fixed columns, FORMAT, then one column per person: 29 columns for 20 people. The first three variants, skipping the long INFO column, for the first five people:

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 45 | tail -n 3 | cut -f 1-7,9-14
chr22   19000085    22:19000085:A:G A   G   .   .   GT  0|0 0|0 0|1 0|0 0|0
chr22   19000359    22:19000359:A:G A   G   .   .   GT  0|0 0|0 0|0 0|0 0|0
chr22   19001039    22:19001039:T:A T   A   .   .   GT  1|1 0|0 0|1 0|1 1|0
Column First variant Meaning
CHROM chr22 Chromosome
POS 19000085 Position, counting from 1
ID 22:19000085:A:G An ID (here chromosome:position:REF:ALT; often an rsID such as rs4680)
REF A The base in the reference genome
ALT G The other allele seen in these people
QUAL . Quality of the call (. means missing; not stored in this file)
FILTER . PASS or the name of a failed filter (missing here)
INFO see below Facts about the site, as KEY=value pairs
FORMAT GT What each person’s column holds: here just GT, the genotype
zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 43 | tail -n 1 | cut -f 8
AC=1;AF=0.025;AN=40;AF_EUR_unrel=0;AF_EAS_unrel=0;AF_AMR_unrel=0.00144092;AF_SAS_unrel=0;AF_AFR_unrel=0.0748865

AN=40 alleles were called (20 people, two copies each) and AC=1 of them is a G, so AF=0.025. The AF_..._unrel values are frequencies in 2,504 unrelated 1000 Genomes people per super-population: this G is rare except in Africans (7.5%), and our one carrier, NA18488, is Yoruba.

A genotype is two alleles, one per chromosome copy: 0 is REF and 1 is ALT. So 0|0 is homozygous reference, 0|1 or 1|0 heterozygous, 1|1 homozygous ALT. | means phased (we know which copy carries which allele); / means unphased.

Now the family. Columns 21, 22 and 23 are NA12878, her father NA12891 and her mother NA12892:

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | head -n 47 | tail -n 6 | cut -f 2,4,5,21-23
POS REF ALT NA12878 NA12891 NA12892
19000085    A   G   0|0 0|0 0|0
19000359    A   G   0|0 0|0 0|0
19001039    T   A   1|1 1|0 1|0
19001507    A   G   1|1 1|0 1|0
19001685    A   C   0|1 0|0 1|0

At 19001039, NA12878 is 1|1, two copies of the A, and each parent carries one (1|0): she got one from each. At 19001685 she is 0|1; her father has no C (0|0) and her mother has one (1|0), so her C came from her mother. Mendel, in a text file.

How many variants? Count the lines that do not start with #; -v inverts the match:

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | grep -v -c '^#'
11955

11,955 variants across the 20 people.

Variant callers also fill in QUAL, FILTER and per-sample details. The first variants called from NA12878’s own reads:

zcat data/variants/NA12878.chr22_calls.vcf.gz | grep -v '^#' | head -n 6 | cut -f 1-7,9,10
chr22   19700475    .   C   T   137.915 PASS    GT:PL:DP:AD 0/1:171,0,255:25:17,8
chr22   19700948    .   AAGAGAGAGAGAGAG AAGAGAGAGAG 178.336 PASS    GT:PL:DP:AD 0/1:211,0,148:23:14,9
chr22   19701025    .   GAGAAAAGAAAAGAAAAGAAAAGA    GAGAAAAGAAAAGAAAAGAAAAGAAAAGA   138.39  PASS    GT:PL:DP:AD 0/1:171,0,142:22:14,8
chr22   19701059    .   CAAAAAAAAAAAA   CAAAAAAAAAAAAA,CAAAAAAAAAAAAAA  149.748 PASS    GT:PL:DP:AD 1/2:210,61,44,164,0,157:17:2,10,5
chr22   19701613    .   G   A   180.172 PASS    GT:PL:DP:AD 0/1:213,0,255:26:16,10
chr22   19701945    .   G   C   225.417 PASS    GT:PL:DP:AD 1/1:255,87,0:29:0,29

The first is a C to T change with QUAL 137.9 that passed the filters (PASS). FORMAT GT:PL:DP:AD gives the order of the values after it: genotype 0/1 (heterozygous, unphased), PL (genotype likelihoods; skip them for now), depth DP 25 reads, and allele depths AD 17,8: 17 reads show C and 8 show T. Rows 2 and 3 are a deletion and an insertion (REF and ALT differ in length), row 4 has two ALT alleles (1/2), and row 6 is homozygous: all 29 reads show the C.

3.9 SAM and BAM: aligned reads

SAM files hold aligned reads: where each read landed on the genome and how well it fit. Header lines come first, starting with @:

head -n 5 data/reads/NA12878.small.sam | cut -c 1-90
@HD VN:1.6  SO:coordinate
@PG ID:novoalign    PN:novoalign    VN:V3.02.07 CL:novoalign -d /cluster/ifs/projects/Genomes/GI
@SQ SN:chr22    LN:50818468 AS:GRCh38_full_plus_hs38d1_analysis_set_minus_alts
@CO Sub-sampled fraction=0.1 seed=7
@RG ID:HG001    SM:NA12878  PL:ILLUMINA LB:HG001_300x

@HD: format version, sorted by coordinate. @PG: the aligner (novoalign). @SQ: the reference, chr22, 50,818,468 bases, the same as our FASTA. @CO: a comment. @RG: the read group, with the sample name (SM) NA12878. Now the reads:

grep -v '^@' data/reads/NA12878.small.sam | head -n 3 | cut -f 1-9
HISEQ1:12:H8GVUADXX:1:2114:20050:45894  99  chr22   19949853    70  148M    =   19950092    387
HISEQ1:16:H948VADXX:2:2206:15924:83090  83  chr22   19949854    70  148M    =   19949535    -467
HWI-D00360:5:H814YADXX:1:1105:9607:59857    163 chr22   19949857    70  148M    =   19950307    598
Column Name First read Meaning
1 QNAME HISEQ1:12:H8GVUADXX:... Read name
2 FLAG 99 A number that packs yes/no facts about the read (below)
3 RNAME chr22 Chromosome it aligned to
4 POS 19949853 Leftmost aligned position, counting from 1
5 MAPQ 70 How sure the aligner is that the read belongs here (0 means it could equally belong elsewhere)
6 CIGAR 148M How the read lines up with the reference (below)
7 RNEXT = Chromosome of its mate (= means the same one)
8 PNEXT 19950092 Position of its mate
9 TLEN 387 Length of the DNA fragment (negative for the mate on the right)
10 SEQ The read sequence
11 QUAL Its quality string, as in FASTQ

Position 19,949,853 is inside COMT (19,941,371 to 19,969,975, from the GTF): these are NA12878’s reads from her COMT gene.

FLAG adds up powers of two, each a yes/no fact. 99 = 1 + 2 + 32 + 64: paired (1), aligned as a proper pair (2), mate on the reverse strand (32), first read of the pair (64). The second read’s 83 = 1 + 2 + 16 + 64: this time the read itself is on the reverse strand (16), and its mate is forward. Don’t memorize them: Explain SAM Flags decodes any number.

CIGAR describes the alignment in counts and letters. 148M: all 148 bases align (M is “match”, mismatches included). A more interesting read, on line 67:

head -n 67 data/reads/NA12878.small.sam | tail -n 1 | cut -f 1-9
HISEQ1:15:H9258ADXX:1:2108:12526:27465  99  chr22   19950139    70  103M4I40M1S =   19950645    654

103M4I40M1S: 103 bases align, 4 are Inserted in the read (not in the reference), 40 more align, and the last base is Soft-clipped (in the read, but not aligned). 103 + 4 + 40 + 1 = 148, the read length.

BAM is the same information in compressed binary form: smaller and faster, but not text. head -c 32 takes the first 32 bytes, and cat -v shows the unprintable ones:

head -c 32 data/reads/NA12878.chr22.bam | cat -v
^_M-^K^H^D^@^@^@^@^@M-^?^F^@BC^B^@M-%^CM-5M-^V=M-^OM-cD^XM-G^GM-^NM-[=^G^]

Garbage to us. (The first two bytes, ^_M-^K, are the “magic number” that starts every gzip file.) To read a BAM, use samtools, which turns it back into SAM text:

samtools view data/reads/NA12878.chr22.bam | head -n 2 | cut -f 1-9
samtools view -c data/reads/NA12878.chr22.bam
HISEQ1:13:H8G92ADXX:2:2106:3837:29737   83  chr22   19699854    70  148M    =   19699295    -707
HISEQ1:17:H947YADXX:1:1106:11929:62324  83  chr22   19699875    70  110M19I19M  =   19699404    -600
52318

52,318 reads, covering chr22 from 19.70 to 20.00 million bases, from the TBX1 gene to COMT. Lesson 10 does much more with samtools.

3.10 The formats at a glance

Format Extensions Counts positions from One record is Count records with
FASTA .fa .fasta .faa (regions are given 1-based) a > line plus its sequence lines grep -c '>' file
FASTQ .fastq.gz .fq.gz n/a 4 lines zcat file | wc -l, then divide by 4
BED, narrowPeak .bed .narrowPeak 0, end not included 1 line wc -l file (if there is no header)
GTF .gtf.gz 1, both ends included 1 line zcat file | grep -v -c '^#'
GFF3 .gff3.gz 1, both ends included 1 line zcat file | grep -v -c '^#'
VCF .vcf.gz 1 1 line per variant site zcat file | grep -v -c '^#'
SAM .sam 1 1 line per alignment grep -v -c '^@' file
BAM .bam 1 (as shown by samtools) binary samtools view -c file

3.11 Your turn

Save each answer with > name.txt at the end of the command, and the box under the question ticks itself when it’s right.

1. How many people are in data/variants/samples.tsv? Don’t count the header. Save the number to people.txt.

tail -n +2 data/variants/samples.tsv | wc -l
20
  1. tail -n +2 drops the header line before wc -l counts.

To tick the box, save the answer:

tail -n +2 data/variants/samples.tsv | wc -l > people.txt

2. Look at the first read of data/reads/SRR2584863_1.fastq.gz. What is the quality character of its very last base, and what is that base’s Phred score? Save the character to last_quality.txt and the score to phred.txt.

zcat data/reads/SRR2584863_1.fastq.gz | head -n 4
@SRR2584863.1 HWI-ST957:244:H73TDADXX:1:1101:4712:2181/1
TTCACATCCTGACCATTCAGTTGAGCAAAATAGTTCTTCAGTGCCTGTTTAACCGAGTCACGCAGGGGTTTTTGGGTTACCTGATCCTGAGAGTTAACGGTAGAAACGGTCAGTACGTCAGAATTTACGCGTTGTTCGAACATAGTTCTG
+
CCCFFFFFGHHHHJIJJJJIJJJIIJJJJIIIJJGFIIIJEDDFEGGJIFHHJIJJDECCGGEGIIJFHFFFACD:BBBDDACCCCAA@@CA@C>C3>@5(8&>C:9?8+89<4(:83825C(:A#########################

It ends in #, Q2: that base is more likely wrong than right. Quality often drops toward the end of a read; this one ends in a long run of #.

To tick the box, save the answers (the quotes matter: without them, the shell reads # as the start of a comment):

echo '#' > last_quality.txt
echo 2 > phred.txt

3. What is the strongest CTCF peak in K562 cells (data/peaks/ctcf_k562.narrowPeak)? Give its position and its width in bases. Save its chromosome, start and end to peak.txt, and its width to peak_width.txt.

head -n 1 data/peaks/ctcf_k562.narrowPeak
chr22   20564140    20564886    .   1000    .   784.65941   -1.00000    4.65032 347

The file is sorted by signal, so line 1 is the strongest peak: chr22, 20564140 to 20564886. BED is 0-based and half-open, so it is 20564886 − 20564140 = 746 bases wide, no “+ 1”. At 20.56 million bases, it is inside the 22q11.2 region.

To tick the box, save the answers:

head -n 1 data/peaks/ctcf_k562.narrowPeak | cut -f 1-3 > peak.txt
echo 746 > peak_width.txt

4. Where is the gene TBX1 in the GENCODE annotation, and how long is it? Save its chromosome, start, end and strand to tbx1.txt, and its length to tbx1_length.txt.

zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "TBX1";' | cut -f 1-8
chr22   HAVANA  gene    19756703    19783593    .   +   .

chr22, 19756703 to 19783593, + strand. GTF is 1-based and includes both ends, so it is 19783593 − 19756703 + 1 = 26,891 bases. TBX1 is a key gene behind many features of 22q11.2 deletion syndrome, including heart defects.

To tick the box, save the answers:

zcat data/annotation/gencode.v50.chr22.gtf.gz | grep -m 1 'gene_name "TBX1";' | cut -f 1,4,5,7 > tbx1.txt
echo 26891 > tbx1_length.txt

5. At position 19002241 of the 22q11.2 VCF, which parent gave NA12878 her ALT allele? (Columns 21, 22 and 23 are NA12878, her father and her mother.) Save father or mother to alt_parent.txt.

zcat data/variants/1kgp.chr22_22q11.20samples.vcf.gz | grep -m 1 '19002241' | cut -f 2,4,5,21-23
19002241    C   T   1|0 1|0 0|0

NA12878 is 1|0, her father NA12891 1|0, her mother NA12892 0|0. Her mother has no T to give, so it came from her father.

To tick the box, save the answer:

echo father > alt_parent.txt

6. (Stretch) Check the length of chromosome 22 yourself, using only wc and tail on data/genome/chr22.fa. Every sequence line holds 50 bases except the last one. Do you get the 50,818,468 bases that the .fai index reports? Save the length you work out to chr22_length.txt.

wc -l data/genome/chr22.fa
tail -n 1 data/genome/chr22.fa | wc -c
1016371 data/genome/chr22.fa
19

1,016,371 lines minus the name line leaves 1,016,370 sequence lines. The last one has 19 bytes: 18 bases plus the newline. So 1,016,369 × 50 + 18 = 50,818,468 bases. It matches.

To tick the box, save the answer:

echo $(( 1016369 * 50 + 18 )) > chr22_length.txt

3.12 Summary

  • Look before you analyze: head, tail, less -S and cat -A answer most questions in seconds, whatever the file size.
  • tail -n +2 skips a header; head -n N | tail -n K cuts out any range of lines. Watch for off-by-one errors.
  • wc -l counts lines. Always ask whether the count includes a header.
  • Keep files compressed: zcat, zless and zgrep read .gz files directly. On a Mac, use gzip -dc.
  • cat -A reveals tabs (^I), Windows line endings (^M) and other invisible problems.
  • BED is 0-based and half-open; GTF, GFF3, VCF and SAM are 1-based and include both ends.
  • One record is one line in BED, GTF, VCF and SAM; two or more lines in FASTA; exactly four lines in FASTQ.
  • Check chromosome names (chr22 or 22) before you combine files.

3.13 Cheat sheet

Command What it does
cat file Print a whole (small) file
cat -n file Print with line numbers
cat -A file Show tabs as ^I, line ends as $, Windows \r as ^M
cat -v Show unprintable bytes
head -n 5 file First 5 lines
head -c 32 file First 32 bytes
tail -n 5 file Last 5 lines
tail -n +2 file Everything from line 2 on (skip a header)
head -n N file | tail -n K The K lines that end at line N
less -S file Scroll through a file without wrapping lines (q quits)
wc file Count lines, words and bytes
wc -l file / wc -l < file Count lines (with / without the file name)
wc -c file Count bytes
zcat file.gz Decompress to the screen; the file stays compressed
gzip -dc file.gz Same as zcat (works on a Mac)
zless -S file.gz less for compressed files (here: zcat file.gz | less -S)
zgrep -m 1 'pattern' file.gz First line matching a pattern in a compressed file (here: zcat file.gz | grep -m 1 'pattern')
gunzip -k file.gz Decompress to a file, keeping the .gz
gzip file Compress a file (replaces it with file.gz)
column -t Line up columns for reading
cut -f 1-3 Keep tab-separated fields 1 to 3
cut -c 1-80 Keep the first 80 characters of each line
grep -c 'pattern' file Count lines that contain a pattern
grep -v -c '^#' file Count lines that don’t start with #
samtools view file.bam Print a BAM file as SAM text
samtools view -c file.bam Count the reads in a BAM file