Skip to content

awk

awk reads its input one record at a time, splits each record into fields, and runs every action whose pattern matches. A record is a line and fields are split on whitespace unless you say otherwise. Most bioinformatics files are line-oriented tables, so awk can count reads, filter variants, and summarize counts without leaving the shell.

The examples ran with GNU awk 5.2.1, which is the awk on most Linux systems. macOS ships BSD awk, so the one recipe that needs a GNU extension says so.

Task One-liner
Print a column awk '{print $3}' file
Print the last column awk '{print $NF}' file
Tab-separated input and output awk -F'\t' -v OFS='\t' '{print $1, $3}' file
Skip the header awk 'NR > 1' file
Count lines awk 'END {print NR}' file
Filter on a number awk -F'\t' '$6 >= 30' file.vcf
Pass a shell variable awk -v cutoff="$p" '$5 < cutoff' file
Sum a column awk '{s += $3} END {print s}' file
Sum per key awk '{s[$1] += $3} END {for (k in s) print k, s[k]}' file | sort
Mean of a column awk '{s += $3; n++} END {print s / n}' file
Rows whose key is in a list awk 'FNR == NR {k[$1]; next} $1 in k' list file
Count FASTA records awk '/^>/ {n++} END {print n}' file.fa
Count FASTQ reads awk 'END {print NR / 4}' file.fq
FASTQ read lengths awk 'NR % 4 == 2 {print length($0)}' file.fq
FASTQ to FASTA awk 'NR % 4 == 1 {print ">" substr($1, 2)} NR % 4 == 2' file.fq
Variants per chromosome awk '!/^#/ {n[$1]++} END {for (c in n) print c, n[c]}' file.vcf
Total BED length awk '{t += $3 - $2} END {print t}' file.bed

Paste these blocks into an empty directory to follow along. The heredocs use | between columns and tr turns each one into a tab, so the files keep their tabs after a copy from the browser.

A long-format count table and a sample sheet:

Terminal window
tr '|' '\t' > counts.tsv <<'EOF'
gene|sample|count
TP53|ctrl_1|120
TP53|trt_1|98
BRCA1|ctrl_1|45
BRCA1|trt_1|60
EGFR|ctrl_1|200
EGFR|trt_1|240
MYC|ctrl_1|30
MYC|trt_1|28
GAPDH|ctrl_1|1500
GAPDH|trt_1|1480
EOF
tr '|' '\t' > samples.tsv <<'EOF'
sample|condition|batch
ctrl_1|control|b1
trt_1|treated|b1
EOF
printf '%s\n' TP53 MYC > genes_of_interest.txt

A FASTA file whose third record wraps over two lines:

Terminal window
cat > sample.fa <<'EOF'
>seq1 TP53 fragment
ATGGAGGAGCCGCAGTCAGATCCTAGC
>seq2 BRCA1 fragment
GATTTATCTGCTCTTCGCGTTGAAGAA
>seq3 EGFR fragment
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC
EOF

A FASTQ file with four reads of different lengths and qualities, and a gzipped copy:

Terminal window
cat > reads.fq <<'EOF'
@read1
ACGTACGTAC
+
IIIIIIIIII
@read2
GGCCTTAAGGCC
+
IIIII#######
@read3
TTGA
+
????
@read4
ACGTTGCAACGTTGCAACGT
+
IIIIIIIIIIIIIIIIII55
EOF
gzip -k reads.fq

A sites-only VCF. The last record lists AF before DP in its INFO column:

Terminal window
tr '|' '\t' > sample.vcf <<'EOF'
##fileformat=VCFv4.2
##INFO=<ID=DP,Number=1,Type=Integer,Description="Read depth">
##INFO=<ID=AF,Number=A,Type=Float,Description="Allele frequency">
##FILTER=<ID=LowQual,Description="QUAL below 30">
#CHROM|POS|ID|REF|ALT|QUAL|FILTER|INFO
chr1|14653|.|C|T|100|PASS|DP=30;AF=0.50
chr7|55191822|.|T|G|210|PASS|DP=95;AF=0.45
chr13|32316000|.|G|A|250|PASS|DP=80;AF=0.48
chr17|7674220|.|C|T|300|PASS|DP=120;AF=0.51
chr17|7675088|.|C|T|18|LowQual|DP=6;AF=0.17
chr17|43045712|.|T|C|95|PASS|AF=1.00;DP=40
EOF

An unsorted BED file of six peaks. peak2 and peak5 overlap, and peak6 starts where peak3 ends:

Terminal window
tr '|' '\t' > regions.bed <<'EOF'
chr2|100|200|peak1
chr1|50|150|peak2
chr1|300|400|peak3
chr3|500|700|peak4
chr1|120|180|peak5
chr1|400|450|peak6
EOF

$0 is the whole record, $1 to $NF are the fields, NF is the number of fields, and NR is the record number. BEGIN runs before the first record and END after the last.

Terminal window
awk '{print NR, NF, $0}' counts.tsv | head -n 4
1 3 gene sample count
2 3 TP53 ctrl_1 120
3 3 TP53 trt_1 98
4 3 BRCA1 ctrl_1 45

-F'\t' splits on tabs only, so a field that contains a space stays whole. NR > 1 skips the header:

Terminal window
awk -F'\t' 'NR > 1 {print $1, $3}' counts.tsv | head -n 4
TP53 120
TP53 98
BRCA1 45
BRCA1 60

print $1, $3 joins fields with OFS, a space by default. Assigning $1 = $1 rebuilds the record with the new separator, which turns space-separated text into a TSV:

Terminal window
printf 'TP53 120\nMYC 30\n' | awk -v OFS='\t' '{$1 = $1; print}'
TP53 120
MYC 30

Quote the shell variable and hand it in with -v. Do not paste it into the awk program text.

Terminal window
min_count=100
awk -F'\t' -v min="$min_count" 'NR > 1 && $3 >= min' counts.tsv
TP53 ctrl_1 120
EGFR ctrl_1 200
EGFR trt_1 240
GAPDH ctrl_1 1500
GAPDH trt_1 1480

A SLURM array task uses this to read its own line of a sample sheet. The header is line 1, so task 2 reads line 3:

Terminal window
task_id=2
awk -F'\t' -v r="$((task_id + 1))" 'NR == r {print $1, $2}' samples.tsv
trt_1 treated

Column order differs between tools and versions. Look the column up in the header line once:

Terminal window
awk -F'\t' -v col=count '
NR == 1 {for (i = 1; i <= NF; i++) if ($i == col) c = i; next}
{print $1, $c}' counts.tsv | head -n 3
TP53 120
TP53 98
BRCA1 45
Terminal window
awk -F'\t' 'NR > 1 {total += $3} END {print total}' counts.tsv
3801

An associative array holds one running sum per gene. for (g in sum) visits keys in no fixed order, so pipe the result through sort:

Terminal window
awk -F'\t' 'NR > 1 {sum[$1] += $3} END {for (g in sum) print g, sum[g]}' \
counts.tsv | sort
BRCA1 105
EGFR 440
GAPDH 2980
MYC 58
TP53 218

Sort by the summed value instead, largest first:

Terminal window
awk -F'\t' -v OFS='\t' 'NR > 1 {sum[$1] += $3}
END {for (g in sum) print g, sum[g]}' counts.tsv | sort -k2,2nr
GAPDH 2980
EGFR 440
TP53 218
BRCA1 105
MYC 58

GNU awk can order the loop itself through PROCINFO["sorted_in"]. This is a gawk extension, so BSD awk on macOS ignores it and keeps the unsorted order.

Terminal window
awk -F'\t' 'NR > 1 {sum[$1] += $3}
END {
PROCINFO["sorted_in"] = "@ind_str_asc"
for (g in sum) print g, sum[g]
}' counts.tsv
BRCA1 105
EGFR 440
GAPDH 2980
MYC 58
TP53 218

printf controls the number format; a bare print of sum / n uses up to six significant digits.

Terminal window
awk -F'\t' 'NR > 1 {
n++; sum += $3
if (n == 1 || $3 < min) min = $3
if (n == 1 || $3 > max) max = $3
}
END {printf "n=%d mean=%.1f min=%d max=%d\n", n, sum / n, min, max}' \
counts.tsv
n=10 mean=380.1 min=28 max=1500

FNR restarts at 1 for each input file while NR keeps counting, so FNR == NR is true only while awk reads the first file, as long as that file is not empty. That idiom loads a lookup table, and next skips the rest of the program for those lines.

Terminal window
awk -F'\t' 'FNR == NR {keep[$1]; next} $1 in keep' \
genes_of_interest.txt counts.tsv
TP53 ctrl_1 120
TP53 trt_1 98
MYC ctrl_1 30
MYC trt_1 28
Terminal window
awk -F'\t' -v OFS='\t' '
FNR == NR {condition[$1] = $2; next}
FNR == 1 {print $0, "condition"; next}
{print $0, condition[$2]}' samples.tsv counts.tsv
gene sample count condition
TP53 ctrl_1 120 control
TP53 trt_1 98 treated
BRCA1 ctrl_1 45 control
BRCA1 trt_1 60 treated
EGFR ctrl_1 200 control
EGFR trt_1 240 treated
MYC ctrl_1 30 control
MYC trt_1 28 treated
GAPDH ctrl_1 1500 control
GAPDH trt_1 1480 treated
Terminal window
awk '/^>/ {n++} END {print n}' sample.fa
3

Print the previous record when a new header arrives, and the last one in END. This handles wrapped records:

Terminal window
awk '/^>/ {if (id) print id, len; id = substr($1, 2); len = 0; next}
{len += length($0)}
END {if (id) print id, len}' sample.fa
seq1 27
seq2 27
seq3 54

gsub returns the number of replacements it made, so it doubles as a counter. It runs on a copy because it also edits the string:

Terminal window
awk '/^>/ {
if (id) printf "%s\t%.3f\n", id, gc / len
id = substr($1, 2); gc = 0; len = 0; next
}
{len += length($0); s = $0; gc += gsub(/[GCgc]/, "", s)}
END {if (id) printf "%s\t%.3f\n", id, gc / len}' sample.fa
seq1 0.593
seq2 0.407
seq3 0.778

With RS = ">" each FASTA entry becomes one record, newlines included, and $1 is the ID:

Terminal window
awk 'BEGIN {RS = ">"; ORS = ""} $1 == "seq3" {print ">" $0}' sample.fa
>seq3 EGFR fragment
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC
Terminal window
awk '/^>/ {if (seq) print seq; print; seq = ""; next}
{seq = seq $0}
END {if (seq) print seq}' sample.fa
>seq1 TP53 fragment
ATGGAGGAGCCGCAGTCAGATCCTAGC
>seq2 BRCA1 fragment
GATTTATCTGCTCTTCGCGTTGAAGAA
>seq3 EGFR fragment
ATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTC

A FASTQ record is four lines: header, sequence, +, and quality. NR % 4 picks one of them.

Terminal window
awk 'END {print NR / 4}' reads.fq
4
Terminal window
awk 'NR % 4 == 2 {print length($0)}' reads.fq | sort -n | uniq -c
1 4
1 10
1 12
1 20
Terminal window
awk 'NR % 4 == 1 {print ">" substr($1, 2)} NR % 4 == 2 {print}' reads.fq
>read1
ACGTACGTAC
>read2
GGCCTTAAGGCC
>read3
TTGA
>read4
ACGTTGCAACGTTGCAACGT

The BEGIN block builds a table from each Phred+33 character to its score, which works in any POSIX awk. This keeps reads whose mean quality is at least 30. For real data, seqkit or fastp does the same job faster.

Terminal window
awk 'BEGIN {for (i = 33; i <= 126; i++) phred[sprintf("%c", i)] = i - 33}
NR % 4 == 1 {head = $0}
NR % 4 == 2 {seq = $0}
NR % 4 == 0 {
total = 0
for (i = 1; i <= length($0); i++) total += phred[substr($0, i, 1)]
if (total / length($0) >= 30) print head "\n" seq "\n+\n" $0
}' reads.fq
@read1
ACGTACGTAC
+
IIIIIIIIII
@read3
TTGA
+
????
@read4
ACGTTGCAACGTTGCAACGT
+
IIIIIIIIIIIIIIIIII55

awk does not decompress, so let zcat feed it:

Terminal window
zcat reads.fq.gz | awk 'NR % 4 == 2 {bases += length($0)}
END {print "reads=" NR / 4, "bases=" bases}'
reads=4 bases=46

Header lines start with ##, the column line starts with #CHROM, and the records are tab-separated: CHROM, POS, ID, REF, ALT, QUAL, FILTER, INFO.

sort -k1,1V puts chr7 before chr13:

Terminal window
awk -F'\t' '!/^#/ {n[$1]++} END {for (c in n) print c, n[c]}' sample.vcf \
| sort -k1,1V
chr1 1
chr7 1
chr13 1
chr17 3

/^#/ || passes every header line through, so the output is still a valid VCF:

Terminal window
awk -F'\t' '/^#/ || $6 >= 30' sample.vcf
##fileformat=VCFv4.2
##INFO=<ID=DP,Number=1,Type=Integer,Description="Read depth">
##INFO=<ID=AF,Number=A,Type=Float,Description="Allele frequency">
##FILTER=<ID=LowQual,Description="QUAL below 30">
#CHROM POS ID REF ALT QUAL FILTER INFO
chr1 14653 . C T 100 PASS DP=30;AF=0.50
chr7 55191822 . T G 210 PASS DP=95;AF=0.45
chr13 32316000 . G A 250 PASS DP=80;AF=0.48
chr17 7674220 . C T 300 PASS DP=120;AF=0.51
chr17 43045712 . T C 95 PASS AF=1.00;DP=40

Split the INFO column on ; and look for the key, because the order of the keys is not fixed. bcftools query -f '%CHROM\t%POS\t%INFO/DP\n' is the standard tool for this on real files.

Terminal window
awk -F'\t' '!/^#/ {
dp = "NA"
n = split($8, kv, ";")
for (i = 1; i <= n; i++) if (kv[i] ~ /^DP=/) dp = substr(kv[i], 4)
print $1, $2, dp
}' sample.vcf
chr1 14653 30
chr7 55191822 95
chr13 32316000 80
chr17 7674220 120
chr17 7675088 6
chr17 43045712 40

BED is tab-separated with chromosome, start, and end first. Starts are 0-based and ends are exclusive, so the length of a record is $3 - $2.

Terminal window
awk '{total += $3 - $2} END {print total}' regions.bed
610

This sum counts the bases where peak2 and peak5 overlap twice.

Sort a BED file before any tool that walks intervals in order, including the merge below and bedtools merge:

Terminal window
sort -k1,1 -k2,2n regions.bed
chr1 50 150 peak2
chr1 120 180 peak5
chr1 300 400 peak3
chr1 400 450 peak6
chr2 100 200 peak1
chr3 500 700 peak4

Track the open interval and print it when the next record starts after its end or on another chromosome. Overlapping and book-ended intervals both merge, as they do in bedtools merge:

Terminal window
sort -k1,1 -k2,2n regions.bed |
awk -v OFS='\t' '
$1 != chrom || $2 > end {
if (chrom != "") print chrom, start, end
chrom = $1; start = $2; end = $3
next
}
$3 > end {end = $3}
END {if (chrom != "") print chrom, start, end}'
chr1 50 180
chr1 300 450
chr2 100 200
chr3 500 700

samtools, IGV, and most genome browsers take chr:start-end with a 1-based start:

Terminal window
awk '{printf "%s:%d-%d\n", $1, $2 + 1, $3}' regions.bed
chr2:101-200
chr1:51-150
chr1:301-400
chr3:501-700
chr1:121-180
chr1:401-450
Tool Best at Avoid for
grep Selecting lines by pattern Arithmetic, logic across columns
sed Substitution and line edits Counting, sums, grouping
awk Per-column logic, arithmetic, group counts Edits that span many lines

If the question is which lines, use grep. If it is how to change the text, use sed. If it needs the columns, use awk.

The GNU awk manual explains records, field separators, associative arrays, and the distinction between NR and FNR. Those sections explain the count summaries and two-file lookups here. Its string-function and printf references describe the operations used by the sequence and quality examples.

The GNU sort reference defines field keys and numeric order. Read it before the interval merge, whose result depends on chromosome and start order.