Level 2 · Code & compute · Topic 2 of 6

Text processing and Bash scripting

grep, cut, sort, awk and pipes on FASTA, GFF and VCF files, then safe, reusable scripts.

  • About 90 minutes
  • 7 practice terminals · 29 checked tasks
  • 2 terminal recordings
  • 10-question check
  • Runs in your browser

What you will learn

  • Combine commands with pipes, and send output and error messages to files with redirection.
  • Search text with grep and regular expressions: anchors, character classes and repetition.
  • Select, sort and count columns with cut, sort, uniq and wc, and reshape text with tr and paste.
  • Edit streams with sed, and compute on columns with awk: filters, sums, means and lengths.
  • Repeat work with variables, for and while loops, and make decisions with if and test.
  • Write safe, reusable Bash scripts that take arguments, check their input, stop on errors and report them.

Before you start: Topic 2.1: the shell, paths, and looking inside files with head, wc and zcat. Basic familiarity with FASTA, FASTQ and GFF files from Level 1 helps.

Small tools, joined together

In 1978, introducing a special issue on the Unix operating system, Doug McIlroy and his colleagues described the style that made it so productive: make each program do one thing well, and expect the output of every program to become the input to another, as yet unknown, program. Almost fifty years later this is still how most bioinformatics gets done. grep finds lines, cut takes columns, sort orders them and uniq -c counts them, and each is fast, reliable and works on files of any size.

The glue is the pipe, |, which sends one command's output straight into the next. A pipeline is built a step at a time: run the first command, look at its output, add the next step, look again. The recording below builds one on the SARS-CoV-2 annotation to answer a real question: which kinds of features does it contain, and how many of each?

Watch: building a pipeline one step at a time. A recording of a terminal session, with every command run by GNU Bash 5.3 and the GNU grep, coreutils and gawk on the same file you will use below. Download the recording
Read the transcript
learner@quanexas:~$ # Which kinds of features are in the SARS-CoV-2 annotation?
learner@quanexas:~$ cd ~/data/sars-cov-2
learner@quanexas:~/data/sars-cov-2$ # Step 1: drop the comment lines, and peek at the first data lines
learner@quanexas:~/data/sars-cov-2$ grep -v '^#' NC_045512.2.gff3 | head -n 3 | cut -c 1-80
NC_045512.2	RefSeq	region	1	29903	.	+	.	ID=NC_045512.2:1..29903;Dbxref=taxon:269
NC_045512.2	RefSeq	five_prime_UTR	1	265	.	+	.	ID=id-NC_045512.2:1..265;gbkey=5'U
NC_045512.2	RefSeq	gene	266	21555	.	+	.	ID=gene-GU280_gp01;Dbxref=GeneID:4374057
learner@quanexas:~/data/sars-cov-2$ # Step 2: keep only column 3, the feature type
learner@quanexas:~/data/sars-cov-2$ grep -v '^#' NC_045512.2.gff3 | cut -f 3 | head -n 5
region
five_prime_UTR
gene
CDS
CDS
learner@quanexas:~/data/sars-cov-2$ # Step 3: sort, so identical types sit together, then count them
learner@quanexas:~/data/sars-cov-2$ grep -v '^#' NC_045512.2.gff3 | cut -f 3 | sort | uniq -c
      1 
     13 CDS
      1 five_prime_UTR
     11 gene
     27 mature_protein_region_of_CDS
      1 region
      5 stem_loop
      1 three_prime_UTR
learner@quanexas:~/data/sars-cov-2$ # Step 4: most common first
learner@quanexas:~/data/sars-cov-2$ grep -v '^#' NC_045512.2.gff3 | cut -f 3 | sort | uniq -c | sort -nr
     27 mature_protein_region_of_CDS
     13 CDS
     11 gene
      5 stem_loop
      1 three_prime_UTR
      1 region
      1 five_prime_UTR
      1 
learner@quanexas:~/data/sars-cov-2$ # The empty type comes from one blank line in the file
learner@quanexas:~/data/sars-cov-2$ # Gene lengths with awk: end - start + 1, longest first
learner@quanexas:~/data/sars-cov-2$ awk -F '\t' '$3 == "gene" { print $5 - $4 + 1, $4, $5 }' NC_045512.2.gff3 | sort -nr | head -n 4
21290 266 21555
3822 21563 25384
1260 28274 29533
828 25393 26220
learner@quanexas:~/data/sars-cov-2$

Input, output and redirection

Every command has three standard streams. It reads from standard input (stdin), writes its results to standard output (stdout), and writes error messages to standard error (stderr). In a terminal, stdin is the keyboard and both outputs go to the screen; redirection connects them to files and to other commands instead.

You writeWhat happens
cmd > out.txtstdout goes into out.txt, replacing what was there
cmd >> out.txtstdout is added to the end of out.txt
cmd < in.txtstdin comes from in.txt
cmd 2> errors.txtstderr (stream 2) goes into errors.txt; results still go to the screen
cmd > all.txt 2>&1both streams go into all.txt (cmd &> all.txt is short for this)
cmd 2> /dev/nullerror messages are thrown away
cmd1 | cmd2stdout of cmd1 becomes stdin of cmd2; stderr still reaches the screen
cmd | tee out.txtsave a copy in out.txt and pass the output on

Keeping errors separate is deliberate: a pipeline's results stay clean, and you still see what went wrong.

Practice terminal

Redirect output and errors

learner@quanexas: ~
  1. Make a results directory and save the list of datasets in data into results/datasets.txt. Nothing should appear on the screen.

    Hint

    mkdir -p results, then ls data > results/datasets.txt. Join two commands with && or run them one after the other.

    Show the answer
    mkdir -p results && ls data > results/datasets.txt
  2. Add the line checked to the end of that file with echo and >>, then look at it with cat.

    Show the answer
    echo checked >> results/datasets.txt
  3. Run ls data nosuchdir, sending only its error message into results/errors.txt.

    Hint

    Standard error is stream 2: 2>.

    Show the answer
    ls data nosuchdir 2> results/errors.txt
  4. Count the lines of data/sars-cov-2/NC_045512.2.gff3 that are not comments by piping grep -v '^#' into wc -l.

    Show the answer
    grep -v '^#' data/sars-cov-2/NC_045512.2.gff3 | wc -l

Searching with grep and regular expressions

grep PATTERN FILE prints every line of FILE that contains PATTERN. Its options cover most everyday questions:

OptionEffectExample
-ccount matching linesgrep -c '>' seqs.fasta: how many sequences
-vlines that do not matchgrep -v '^#' file.gff3: drop comments
-iignore upper and lower casegrep -i 'kinase'
-nshow line numbersgrep -n 'Name=S;'
-wmatch whole words onlygrep -w 'CDS'
-oprint only the matching partgrep -o 'gene=[^;]*'
-Eextended regular expressionsgrep -E 'ORF(1ab|3a)'
-Ffixed text, no special charactersgrep -F 'NC_045512.2'

The pattern is a regular expression, a small language for describing text. Most characters match themselves; a few have special meanings:

PatternMatches
^ and $the start and the end of the line: ^> is a FASTA header, ^$ an empty line
.any one character (so NC_045512.2 also matches NC_045512x2; use \. or -F for a real dot)
[ACGT] and [^ACGT]one of these characters, and one character that is not one of them
*the item before it, zero or more times: GA*T matches GT, GAT, GAAT…
+, ?, {n}one or more, zero or one, exactly n times (with -E): A{6,} is a run of at least six A
a|b and ( )either alternative, and grouping (with -E)

Put patterns in single quotes so the shell passes them to grep unchanged.

Interactive

Regular expression tester

Type a pattern and watch it match real lines from FASTA, GFF and VCF files. The matching is the same as the practice terminal's grep.

Practice terminal

Search real files

This terminal starts in ~/data.

learner@quanexas: ~/data
  1. Count the sequences in each FASTA file in hbb with grep -c. (Remember the quotes: '>'.)

    Show the answer
    grep -c '>' hbb/*.fasta
  2. Count the comment lines, which start with #, in sars-cov-2/NC_045512.2.gff3.

    Hint

    Anchor the pattern with ^.

    Show the answer
    grep -c '^#' sars-cov-2/NC_045512.2.gff3
  3. Find the lines of the same file that describe the spike gene, Name=S;, showing their line numbers.

    Show the answer
    grep -n 'Name=S;' sars-cov-2/NC_045512.2.gff3
  4. How many variant records are in the ClinVar file hbb-variants/clinvar_20261019_chr11_5220001-5300000.vcf.gz? Decompress it with zcat and count the lines that do not start with #.

    Hint

    -v and -c combine: grep -vc.

    Show the answer
    zcat hbb-variants/clinvar_20261019_chr11_5220001-5300000.vcf.gz | grep -vc '^#'
  5. Count the EcoRI sites, GAATTC, in the E. coli K-12 genome. Join the sequence into one line first (a site can be split across two lines), then print each match on its own line with grep -o and count them.

    Hint

    zcat ... | grep -v '>' | tr -d '\n' | grep -o GAATTC | wc -l

    Show the answer
    zcat ecoli-k12/NC_000913.3.fasta.gz | grep -v '>' | tr -d '\n' | grep -o GAATTC | wc -l

Columns: cut, sort, uniq, tr and paste

Most biological files are tables: GFF, VCF, BED, sample sheets and count matrices have one record per line and fields separated by tabs (or commas, for CSV). A handful of tools answer most questions about them.

CommandWhat it does
cut -f 3keep field 3 (fields are tab-separated unless you set -d, as in cut -d , -f 2); -f 1,4-5 keeps several
sortsort lines; -n numerically, -r in reverse, -k 2,2 on field 2, -t , with a separator, -u unique
uniq -ccollapse identical neighbouring lines and count them, so sort first
wc -lcount lines
tr ACGT TGCAtranslate characters one for one; tr -d '\n' deletes them
paste - - - -join every four lines into one, separated by tabs
rev, column -treverse each line; line columns up for reading

The idiom sort | uniq -c | sort -nr is worth learning by heart: it makes a frequency table, most common first, of whatever you feed it.

Practice terminal

Count, sort and reshape

learner@quanexas: ~/data
  1. Make a frequency table of the feature types (field 3) in sars-cov-2/NC_045512.2.gff3, without the comment lines, with the most common first.

    Hint

    grep -v '^#' ... | cut -f 3 | sort | uniq -c | sort -nr

    Show the answer
    grep -v '^#' sars-cov-2/NC_045512.2.gff3 | cut -f 3 | sort | uniq -c | sort -nr
  2. The 1000 Genomes panel hbb-variants/integrated_call_samples_v3.20130502.ALL.panel lists 2,504 people with their super-population in field 3. Count the people in each super-population. Skip the header line with tail -n +2.

    Show the answer
    cut -f 3 hbb-variants/integrated_call_samples_v3.20130502.ALL.panel | tail -n +2 | sort | uniq -c
  3. Show the 5 genes with the most reads in the first sample (field 2) of pasilla/pasilla_gene_counts.tsv: skip the header, sort numerically on field 2 in reverse, and keep 5 lines.

    Hint

    sort -k2,2nr sorts on field 2 only, numerically, largest first.

    Show the answer
    tail -n +2 pasilla/pasilla_gene_counts.tsv | sort -k2,2nr | head -n 5
  4. Print the reverse complement of GATTACA with echo, tr and rev.

    Show the answer
    echo GATTACA | tr ACGT TGCA | rev
  5. Turn lenski/SRR2584863_1.first10k.fastq.gz into one line per read with paste - - - -, and show the first 2 lines.

    Show the answer
    zcat lenski/SRR2584863_1.first10k.fastq.gz | paste - - - - | head -n 2

Editing streams with sed and computing with awk

sed, the stream editor, changes text as it flows past. Its most used command is substitution, s/old/new/, which replaces the first match on each line (add g to replace them all). It can also pick lines by number: sed -n '2p' prints only line 2, sed '1d' deletes line 1, and the GNU extension sed -n '2~4p' prints line 2 and then every fourth line, which in a FASTQ file is exactly the sequences.

sed 's/^>/>sample1_/' seqs.fasta       # prefix every FASTA header
sed -E 's/gene-(GU280_gp[0-9]+)/\1/' a.gff3   # keep part of a match with ( ) and \1
sed -n '2~4p' reads.fastq              # the sequence lines of a FASTQ file

awk reads a file one line (record) at a time, splits it into fields $1, $2…, and runs a small program on it. A program is a list of pattern { action } pairs: the action runs on every line where the pattern is true. NR is the line number, NF the number of fields, $NF the last field, and BEGIN and END run before the first line and after the last. Set the field separator with -F; for tab-separated files use -F '\t', because by default awk splits on any run of spaces or tabs.

awk -F '\t' '$3 == "gene"' a.gff3                 # filter rows
awk -F '\t' '{ print $1, $4, $5 }' a.gff3          # choose columns
awk -F '\t' 'NR > 1 { s += $2 } END { print s }' counts.tsv   # add up a column
awk 'NR % 4 == 2 { n += length($0) } END { print n / (NR / 4) }' reads.fastq   # mean read length
awk '{ count[$1]++ } END { for (k in count) print k, count[k] }' file   # count values

Between them, grep, cut, sort, sed and awk handle a surprising share of real data wrangling. The explorer below runs real pipelines on the hosted files and shows what each step hands to the next.

Interactive

Pipeline explorer

Choose a pipeline, or write your own, and run it. Each box is one command; the number is how many lines it passed on, and you can open any box to see its output. It runs the practice terminal's shell on the real files.

Practice terminal

sed and awk on real data

learner@quanexas: ~/data
  1. Print the first 3 read sequences of lenski/SRR2584863_1.first10k.fastq.gz with sed -n '2~4p'.

    Show the answer
    zcat lenski/SRR2584863_1.first10k.fastq.gz | sed -n '2~4p' | head -n 3
  2. Print the SARS-CoV-2 FASTA header (head -n 1) with Severe acute respiratory syndrome coronavirus 2 replaced by SARS-CoV-2, using sed.

    Show the answer
    head -n 1 sars-cov-2/NC_045512.2.fasta | sed 's/Severe acute respiratory syndrome coronavirus 2/SARS-CoV-2/'
  3. With awk, print the start (field 4), end (field 5) and length (end − start + 1) of every gene line in sars-cov-2/NC_045512.2.gff3.

    Hint

    awk -F '\t' '$3 == "gene" { print $4, $5, $5 - $4 + 1 }' FILE

    Show the answer
    awk -F '\t' '$3 == "gene" { print $4, $5, $5 - $4 + 1 }' sars-cov-2/NC_045512.2.gff3
  4. Compute the mean read length of the same FASTQ file with awk: add up length($0) on every fourth line starting at line 2, and divide by the number of reads at the end.

    Show the answer
    zcat lenski/SRR2584863_1.first10k.fastq.gz | awk 'NR % 4 == 2 { n++; total += length($0) } END { print total / n }'
  5. Count the G and C bases in the SARS-CoV-2 genome: drop the header, then delete every character except G and C with tr -cd 'GC', and count what is left with wc -c.

    Show the answer
    grep -v '>' sars-cov-2/NC_045512.2.fasta | tr -cd 'GC' | wc -c

Variables, loops and decisions

Bash is also a programming language, and three ideas cover most of what you need.

Variables hold text. Set one with name=value (no spaces around =) and use it with $name, inside double quotes: "$file". Without the quotes, a value containing spaces or wildcards is split and expanded, a classic source of bugs. $( ) captures a command's output, and $(( )) does whole-number arithmetic:

file=data/lenski/SRR2584863_1.first10k.fastq.gz
lines=$(zcat "$file" | wc -l)
echo "$file has $(( lines / 4 )) reads"

A for loop repeats commands for each item in a list, very often a list of files from a wildcard. A while read loop runs once for each line of input, splitting it into variables:

for f in data/hbb/*.fasta; do
  echo "$f: $(grep -c '>' "$f") sequences"
done

tail -n +2 samples.tsv | while read -r sample pop rest; do
  echo "$sample is from $pop"
done

if runs commands only when a test succeeds. [ -f file ] is true if a file exists, [ -d dir ] for a directory, [ -s file ] if it is not empty, [ "$a" = "$b" ] compares text and [ "$n" -gt 10 ] compares numbers. Every command reports success or failure with an exit status, 0 for success, which $? holds and if, && and || act on.

if [ -s "$f" ]; then echo "$f has data"; else echo "$f is empty" >&2; fi
grep -q 'ATG' seq.txt && echo "found a start codon"

Practice terminal

Repeat work with loops

learner@quanexas: ~
  1. Put the path data/sars-cov-2/NC_045512.2.gff3 into a variable called f, then count its lines with wc -l "$f", all on one line (separate the two commands with ;).

    Show the answer
    f=data/sars-cov-2/NC_045512.2.gff3; wc -l "$f"
  2. Loop over the FASTA files in data/hbb and print each file name followed by its number of sequence characters (the lines without >, with newlines removed).

    Hint

    for f in data/hbb/*.fasta; do echo "$f $(grep -v '>' "$f" | tr -d '\n' | wc -c)"; done

    Show the answer
    for f in data/hbb/*.fasta; do echo "$f $(grep -v '>' "$f" | tr -d '\n' | wc -c)"; done
  3. Use a while read loop to print "SAMPLE is from POP" for the first 3 people in data/hbb-variants/integrated_call_samples_v3.20130502.ALL.panel (skip the header line).

    Show the answer
    tail -n +2 data/hbb-variants/integrated_call_samples_v3.20130502.ALL.panel | head -n 3 | while read -r sample pop super sex; do echo "$sample is from $pop"; done
  4. Write an if statement that prints found if data/hbb is a directory and missing otherwise.

    Show the answer
    if [ -d data/hbb ]; then echo found; else echo missing; fi

Writing safe, reusable scripts

Once a pipeline works, save it in a script: a text file of commands that you can run again on new data, share and keep under version control. A good Bash script starts like this:

#!/usr/bin/env bash
# What this script does, and how to run it.
set -euo pipefail

The first line, the shebang, says which program runs the file. set -euo pipefail makes the script stop at the first failing command (-e), treat a misspelt or missing variable as an error (-u), and count a pipeline as failed if any of its commands fails, not just the last (-o pipefail). Without these, a script carries on after errors and can produce plausible-looking results from missing or truncated input.

Scripts take arguments: $1 is the first, $2 the second, $# how many there are and "$@" all of them. Check them before doing any work, and report problems on standard error with a non-zero exit status, so that the person, or the pipeline, running the script knows it failed:

if [[ $# -ne 1 ]]; then
  echo "usage: count_reads.sh FILE.fastq.gz" >&2
  exit 1
fi

Run a script with bash script.sh, or make it executable once with chmod u+x script.sh and run it as ./script.sh. When something goes wrong, bash -x script.sh prints each command as it runs. The free ShellCheck program finds many common mistakes, such as missing quotes, before you run a script at all.

Watch: writing and running a safe script. A recording made with GNU Bash 5.3: a script is written with a here-document, made executable, run on real reads, and run again with missing and wrong arguments to show its error handling. Download the recording
Read the transcript
learner@quanexas:~$ # A script that counts the reads in a gzipped FASTQ file
learner@quanexas:~$ mkdir -p ~/scripts && cd ~
learner@quanexas:~$ cat > scripts/count_reads.sh <<'EOF'
> #!/usr/bin/env bash
> # Count the reads in a gzip-compressed FASTQ file.
> set -euo pipefail
> if [[ $# -ne 1 ]]; then
>   echo "usage: count_reads.sh FILE.fastq.gz" >&2
>   exit 1
> fi
> lines=$(zcat "$1" | wc -l)
> echo "$1: $(( lines / 4 )) reads"
> EOF
learner@quanexas:~$ # Make it executable, then run it
learner@quanexas:~$ chmod u+x scripts/count_reads.sh
learner@quanexas:~$ scripts/count_reads.sh data/lenski/SRR2584863_1.first10k.fastq.gz
data/lenski/SRR2584863_1.first10k.fastq.gz: 10000 reads
learner@quanexas:~$ # Mistakes stop the script with a clear message and a non-zero exit status
learner@quanexas:~$ scripts/count_reads.sh; echo "exit status: $?"
usage: count_reads.sh FILE.fastq.gz
exit status: 1
learner@quanexas:~$ scripts/count_reads.sh missing.fastq.gz; echo "exit status: $?"
gzip: missing.fastq.gz: No such file or directory
exit status: 1
learner@quanexas:~$ # A loop runs it on every file
learner@quanexas:~$ for f in data/lenski/*.fastq.gz; do scripts/count_reads.sh "$f"; done
data/lenski/SRR2584863_1.first10k.fastq.gz: 10000 reads
data/lenski/SRR2584863_2.first10k.fastq.gz: 10000 reads
learner@quanexas:~$

Practice terminal

Your first script

Write the script with nano scripts/gc.sh (Ctrl+O saves, Ctrl+X exits), or paste a here-document as in the recording.

learner@quanexas: ~
  1. Write scripts/gc.sh: a script that prints the GC content of the FASTA file named in $1, as a percentage with two decimals (for the SARS-CoV-2 genome it prints 37.97). Run it with bash scripts/gc.sh data/sars-cov-2/NC_045512.2.fasta.

    Hint

    Build the command line by line: grep -v '>' "$file" | tr -d '\n' gives the sequence as one line; an awk program can then count G and C with gsub and print with printf "%.2f\n".

    Show the answer
    #!/usr/bin/env bash
    # Print the GC content of a FASTA file as a percentage with two decimals.
    set -euo pipefail
    file="$1"
    grep -v '>' "$file" | tr -d '\n' | awk '{ n = length($0); gc = gsub(/[GCgc]/, ""); printf "%.2f\n", 100 * gc / n }'
  2. Make the script executable, then run it as scripts/gc.sh data/hbb/NM_000518.5.fasta.

    Show the answer
    chmod u+x scripts/gc.sh
  3. Improve the script: when it is run without exactly one argument, it should print a usage message on standard error and exit with status 1. Test it with scripts/gc.sh; echo $?.

    Hint

    Test $#, the number of arguments: if [[ $# -ne 1 ]]; then echo "usage: gc.sh FILE.fasta" >&2; exit 1; fi

    Show the answer
    #!/usr/bin/env bash
    # Print the GC content of a FASTA file as a percentage with two decimals.
    set -euo pipefail
    if [[ $# -ne 1 ]]; then
      echo "usage: gc.sh FILE.fasta" >&2
      exit 1
    fi
    file="$1"
    grep -v '>' "$file" | tr -d '\n' | awk '{ n = length($0); gc = gsub(/[GCgc]/, ""); printf "%.2f\n", 100 * gc / n }'

Check your understanding

Ten questions. Score 70% or more to complete this part of the topic. You can retake it as often as you like.

1What does cmd > out.txt 2>&1 do?
2Why does sort data.txt > data.txt leave an empty file?
3Which pattern matches only FASTA header lines?
4Why must you sort before uniq -c?
5What does cut -f 3 file.gff3 print?
6In a FASTQ file, which lines does sed -n '2~4p' print?
7What does awk -F '\t' '$3 == "gene" { n++ } END { print n }' file.gff3 print?
8Why should a variable usually be written "$file" rather than $file?
9What does set -o pipefail change?
10A script is run as ./count.sh and Bash says Permission denied. What is the usual fix?

Mini project: a FASTQ summary script

Write the kind of small, safe script that sits at the start of every sequencing analysis: it summarises a gzipped FASTQ file without ever changing it, refuses bad input with a clear message, and runs over every sample in a loop.

The script, scripts/fastq_stats.sh, takes one .fastq.gz file and prints one tab-separated line: the file name without its directory, the number of reads, the mean read length with one decimal, and the GC percentage with one decimal. For the first Lenski file it prints:

SRR2584863_1.first10k.fastq.gz	10000	150.0	50.6

Run without exactly one argument it prints a usage message on standard error and exits with status 1; given a file that does not exist it does the same with a message naming the file.

Practice terminal

FASTQ summaries for every sample

learner@quanexas: ~
  1. Write scripts/fastq_stats.sh as described above. Use zcat to read the file and one awk program to count the reads, bases and G and C on every fourth line starting at line 2. basename gives the name without its directory.

    Hint

    The core is zcat "$file" | awk -v name="$(basename "$file")" 'NR % 4 == 2 { reads++; bases += length($0); gc += gsub(/[GCgc]/, "") } END { printf "%s\t%d\t%.1f\t%.1f\n", name, reads, bases / reads, 100 * gc / bases }'. Add the argument and file checks before it.

    Show the answer
    #!/usr/bin/env bash
    # Summarise a gzip-compressed FASTQ file: reads, mean read length and GC content.
    # Usage: fastq_stats.sh FILE.fastq.gz   (the input file is only read, never changed)
    set -euo pipefail
    
    if [[ $# -ne 1 ]]; then
      echo "usage: fastq_stats.sh FILE.fastq.gz" >&2
      exit 1
    fi
    file="$1"
    if [[ ! -f "$file" ]]; then
      echo "fastq_stats.sh: $file: no such file" >&2
      exit 1
    fi
    
    zcat "$file" | awk -v name="$(basename "$file")" '
      NR % 4 == 2 { reads++; bases += length($0); gc += gsub(/[GCgc]/, "") }
      END { printf "%s\t%d\t%.1f\t%.1f\n", name, reads, bases / reads, 100 * gc / bases }'
  2. Run the script on every .fastq.gz file in data/lenski with a for loop, and save the results, after a header line file<TAB>reads<TAB>mean_length<TAB>gc_percent, in results/qc.tsv. Grouping commands in { ...; } lets one > collect all their output.

    Hint

    { printf 'file\treads\tmean_length\tgc_percent\n'; for f in data/lenski/*.fastq.gz; do bash scripts/fastq_stats.sh "$f"; done; } > results/qc.tsv

    Show the answer
    { printf 'file\treads\tmean_length\tgc_percent\n'; for f in data/lenski/*.fastq.gz; do bash scripts/fastq_stats.sh "$f"; done; } > results/qc.tsv
  3. Display the table with its columns lined up: column -t results/qc.tsv.

    Show the answer
    column -t results/qc.tsv

Go further

  • Add a fifth column: the number of reads that contain an N (an undetermined base). There are 14 in the first file.
  • Add a check that the file name ends in .fastq.gz, using [[ $file == *.fastq.gz ]].
  • Make the script also append a line to results/qc.log with the date ($(date +%F)) and the file it processed, so you have a record of every run.

Summary and further reading

Key takeaways

  • Small tools joined by pipes do most everyday data wrangling: build a pipeline one step at a time, looking at the output after each step.
  • Every command has stdin, stdout and stderr. > replaces a file, >> appends, 2> captures errors and | feeds the next command. Quote patterns that contain > < | * or spaces.
  • grep searches with regular expressions: ^ and $ anchor, [ ] chooses, * + ? repeat, -v inverts, -c counts and -o extracts.
  • cut, sort, uniq -c, tr and paste answer most questions about tables; sort | uniq -c | sort -nr is a frequency table.
  • sed substitutes and selects lines; awk filters rows and computes on columns, with BEGIN and END for set-up and totals.
  • Scripts make work repeatable: a shebang, set -euo pipefail, quoted variables, checked arguments, errors on stderr and non-zero exit statuses.

Key terms

Data used on this page

References and further reading

  1. McIlroy MD, Pinson EN, Tague BA. UNIX time-sharing system: foreword. Bell System Technical Journal 57, 1899–1904 (1978). doi:10.1002/j.1538-7305.1978.tb02135.x
  2. Thompson K. Regular expression search algorithm. Communications of the ACM 11, 419–422 (1968). doi:10.1145/363347.363387
  3. Aho AV, Kernighan BW, Weinberger PJ. Awk: a pattern scanning and processing language. Software: Practice and Experience 9, 267–279 (1979). doi:10.1002/spe.4380090403
  4. Taschuk M, Wilson G. Ten simple rules for making research software more robust. PLOS Computational Biology 13, e1005412 (2017). doi:10.1371/journal.pcbi.1005412
  5. Brandies PA, Hogg CJ. Ten simple rules for getting started with command-line bioinformatics. PLOS Computational Biology 17, e1008645 (2021). doi:10.1371/journal.pcbi.1008645
  6. Danecek P, et al. The variant call format and VCFtools. Bioinformatics 27, 2156–2158 (2011). doi:10.1093/bioinformatics/btr330
  7. Landrum MJ, et al. ClinVar: improvements to accessing data. Nucleic Acids Research 48, D835–D844 (2020). doi:10.1093/nar/gkz972
  8. Byrska-Bishop M, et al. High-coverage whole-genome sequencing of the expanded 1000 Genomes Project cohort including 602 trios. Cell 185, 3426–3440 (2022). doi:10.1016/j.cell.2022.08.004
  9. Brooks AN, et al. Conservation of an RNA regulatory map between Drosophila and mammals. Genome Research 21, 193–202 (2011). doi:10.1101/gr.108662.110
  10. The Sequence Ontology. Generic Feature Format version 3 (GFF3) specification. github.com
  11. GNU grep, GNU sed and the GNU Awk User’s Guide: the manuals for the tools on this page. www.gnu.org
  12. ShellCheck: a free tool that finds bugs in shell scripts. www.shellcheck.net

Finished the topic?

Pass the check and the exercises, or mark the topic complete yourself. Progress is saved in this browser.