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.
Quick reference
Section titled “Quick reference”| 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 |
Example files
Section titled “Example files”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:
tr '|' '\t' > counts.tsv <<'EOF'gene|sample|countTP53|ctrl_1|120TP53|trt_1|98BRCA1|ctrl_1|45BRCA1|trt_1|60EGFR|ctrl_1|200EGFR|trt_1|240MYC|ctrl_1|30MYC|trt_1|28GAPDH|ctrl_1|1500GAPDH|trt_1|1480EOFtr '|' '\t' > samples.tsv <<'EOF'sample|condition|batchctrl_1|control|b1trt_1|treated|b1EOFprintf '%s\n' TP53 MYC > genes_of_interest.txtA FASTA file whose third record wraps over two lines:
cat > sample.fa <<'EOF'>seq1 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq2 BRCA1 fragmentGATTTATCTGCTCTTCGCGTTGAAGAA>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCEOFA FASTQ file with four reads of different lengths and qualities, and a gzipped copy:
cat > reads.fq <<'EOF'@read1ACGTACGTAC+IIIIIIIIII@read2GGCCTTAAGGCC+IIIII#######@read3TTGA+????@read4ACGTTGCAACGTTGCAACGT+IIIIIIIIIIIIIIIIII55EOFgzip -k reads.fqA sites-only VCF. The last record lists AF before DP in its INFO column:
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|INFOchr1|14653|.|C|T|100|PASS|DP=30;AF=0.50chr7|55191822|.|T|G|210|PASS|DP=95;AF=0.45chr13|32316000|.|G|A|250|PASS|DP=80;AF=0.48chr17|7674220|.|C|T|300|PASS|DP=120;AF=0.51chr17|7675088|.|C|T|18|LowQual|DP=6;AF=0.17chr17|43045712|.|T|C|95|PASS|AF=1.00;DP=40EOFAn unsorted BED file of six peaks. peak2 and peak5 overlap, and peak6 starts where peak3
ends:
tr '|' '\t' > regions.bed <<'EOF'chr2|100|200|peak1chr1|50|150|peak2chr1|300|400|peak3chr3|500|700|peak4chr1|120|180|peak5chr1|400|450|peak6EOFThe basics
Section titled “The basics”$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.
awk '{print NR, NF, $0}' counts.tsv | head -n 41 3 gene sample count2 3 TP53 ctrl_1 1203 3 TP53 trt_1 984 3 BRCA1 ctrl_1 45Set the field separator
Section titled “Set the field separator”-F'\t' splits on tabs only, so a field that contains a space stays whole. NR > 1 skips the
header:
awk -F'\t' 'NR > 1 {print $1, $3}' counts.tsv | head -n 4TP53 120TP53 98BRCA1 45BRCA1 60Set the output separator
Section titled “Set the output separator”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:
printf 'TP53 120\nMYC 30\n' | awk -v OFS='\t' '{$1 = $1; print}'TP53 120MYC 30Pass a shell variable
Section titled “Pass a shell variable”Quote the shell variable and hand it in with -v. Do not paste it into the awk program text.
min_count=100awk -F'\t' -v min="$min_count" 'NR > 1 && $3 >= min' counts.tsvTP53 ctrl_1 120EGFR ctrl_1 200EGFR trt_1 240GAPDH ctrl_1 1500GAPDH trt_1 1480Pick one row by number
Section titled “Pick one row by number”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:
task_id=2awk -F'\t' -v r="$((task_id + 1))" 'NR == r {print $1, $2}' samples.tsvtrt_1 treatedPick a column by its header name
Section titled “Pick a column by its header name”Column order differs between tools and versions. Look the column up in the header line once:
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 3TP53 120TP53 98BRCA1 45Counting and summing
Section titled “Counting and summing”Sum a column
Section titled “Sum a column”awk -F'\t' 'NR > 1 {total += $3} END {print total}' counts.tsv3801Group by a key
Section titled “Group by a key”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:
awk -F'\t' 'NR > 1 {sum[$1] += $3} END {for (g in sum) print g, sum[g]}' \ counts.tsv | sortBRCA1 105EGFR 440GAPDH 2980MYC 58TP53 218Sort by the summed value instead, largest first:
awk -F'\t' -v OFS='\t' 'NR > 1 {sum[$1] += $3} END {for (g in sum) print g, sum[g]}' counts.tsv | sort -k2,2nrGAPDH 2980EGFR 440TP53 218BRCA1 105MYC 58GNU 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.
awk -F'\t' 'NR > 1 {sum[$1] += $3} END { PROCINFO["sorted_in"] = "@ind_str_asc" for (g in sum) print g, sum[g] }' counts.tsvBRCA1 105EGFR 440GAPDH 2980MYC 58TP53 218Column statistics
Section titled “Column statistics”printf controls the number format; a bare print of sum / n uses up to six significant
digits.
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.tsvn=10 mean=380.1 min=28 max=1500Joining two files
Section titled “Joining two files”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.
Keep the rows for a list of genes
Section titled “Keep the rows for a list of genes”awk -F'\t' 'FNR == NR {keep[$1]; next} $1 in keep' \ genes_of_interest.txt counts.tsvTP53 ctrl_1 120TP53 trt_1 98MYC ctrl_1 30MYC trt_1 28Add a column from a sample sheet
Section titled “Add a column from a sample sheet”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.tsvgene sample count conditionTP53 ctrl_1 120 controlTP53 trt_1 98 treatedBRCA1 ctrl_1 45 controlBRCA1 trt_1 60 treatedEGFR ctrl_1 200 controlEGFR trt_1 240 treatedMYC ctrl_1 30 controlMYC trt_1 28 treatedGAPDH ctrl_1 1500 controlGAPDH trt_1 1480 treatedFASTA recipes
Section titled “FASTA recipes”Count records
Section titled “Count records”awk '/^>/ {n++} END {print n}' sample.fa3Sequence lengths
Section titled “Sequence lengths”Print the previous record when a new header arrives, and the last one in END. This handles
wrapped records:
awk '/^>/ {if (id) print id, len; id = substr($1, 2); len = 0; next} {len += length($0)} END {if (id) print id, len}' sample.faseq1 27seq2 27seq3 54GC content
Section titled “GC content”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:
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.faseq1 0.593seq2 0.407seq3 0.778Extract one record by ID
Section titled “Extract one record by ID”With RS = ">" each FASTA entry becomes one record, newlines included, and $1 is the ID:
awk 'BEGIN {RS = ">"; ORS = ""} $1 == "seq3" {print ">" $0}' sample.fa>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCUnwrap to one line per sequence
Section titled “Unwrap to one line per sequence”awk '/^>/ {if (seq) print seq; print; seq = ""; next} {seq = seq $0} END {if (seq) print seq}' sample.fa>seq1 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq2 BRCA1 fragmentGATTTATCTGCTCTTCGCGTTGAAGAA>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCFASTQ recipes
Section titled “FASTQ recipes”A FASTQ record is four lines: header, sequence, +, and quality. NR % 4 picks one of them.
Count reads
Section titled “Count reads”awk 'END {print NR / 4}' reads.fq4Read length histogram
Section titled “Read length histogram”awk 'NR % 4 == 2 {print length($0)}' reads.fq | sort -n | uniq -c 1 4 1 10 1 12 1 20Convert FASTQ to FASTA
Section titled “Convert FASTQ to FASTA”awk 'NR % 4 == 1 {print ">" substr($1, 2)} NR % 4 == 2 {print}' reads.fq>read1ACGTACGTAC>read2GGCCTTAAGGCC>read3TTGA>read4ACGTTGCAACGTTGCAACGTFilter by mean quality
Section titled “Filter by mean quality”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.
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@read1ACGTACGTAC+IIIIIIIIII@read3TTGA+????@read4ACGTTGCAACGTTGCAACGT+IIIIIIIIIIIIIIIIII55Read a gzipped FASTQ
Section titled “Read a gzipped FASTQ”awk does not decompress, so let zcat feed it:
zcat reads.fq.gz | awk 'NR % 4 == 2 {bases += length($0)} END {print "reads=" NR / 4, "bases=" bases}'reads=4 bases=46VCF recipes
Section titled “VCF recipes”Header lines start with ##, the column line starts with #CHROM, and the records are
tab-separated: CHROM, POS, ID, REF, ALT, QUAL, FILTER, INFO.
Variants per chromosome
Section titled “Variants per chromosome”sort -k1,1V puts chr7 before chr13:
awk -F'\t' '!/^#/ {n[$1]++} END {for (c in n) print c, n[c]}' sample.vcf \ | sort -k1,1Vchr1 1chr7 1chr13 1chr17 3Filter by QUAL and keep the header
Section titled “Filter by QUAL and keep the header”/^#/ || passes every header line through, so the output is still a valid VCF:
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 INFOchr1 14653 . C T 100 PASS DP=30;AF=0.50chr7 55191822 . T G 210 PASS DP=95;AF=0.45chr13 32316000 . G A 250 PASS DP=80;AF=0.48chr17 7674220 . C T 300 PASS DP=120;AF=0.51chr17 43045712 . T C 95 PASS AF=1.00;DP=40Extract one INFO key
Section titled “Extract one INFO key”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.
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.vcfchr1 14653 30chr7 55191822 95chr13 32316000 80chr17 7674220 120chr17 7675088 6chr17 43045712 40BED recipes
Section titled “BED recipes”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.
Total length
Section titled “Total length”awk '{total += $3 - $2} END {print total}' regions.bed610This sum counts the bases where peak2 and peak5 overlap twice.
Sort by chromosome and start
Section titled “Sort by chromosome and start”Sort a BED file before any tool that walks intervals in order, including the merge below and
bedtools merge:
sort -k1,1 -k2,2n regions.bedchr1 50 150 peak2chr1 120 180 peak5chr1 300 400 peak3chr1 400 450 peak6chr2 100 200 peak1chr3 500 700 peak4Merge overlapping intervals
Section titled “Merge overlapping intervals”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:
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 180chr1 300 450chr2 100 200chr3 500 700Convert to 1-based region strings
Section titled “Convert to 1-based region strings”samtools, IGV, and most genome browsers take chr:start-end with a 1-based start:
awk '{printf "%s:%d-%d\n", $1, $2 + 1, $3}' regions.bedchr2:101-200chr1:51-150chr1:301-400chr3:501-700chr1:121-180chr1:401-450awk, grep, or sed
Section titled “awk, grep, or sed”| 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.
See also
Section titled “See also”- grep, find & pipes for searching and chaining commands.
- sed for substitution and line edits.
- Text Processing teaches awk alongside cut, sort, and uniq.
- FASTQ: Raw Reads explains Phred scores and the four-line record.
- VCF: Variants covers INFO keys and
bcftools query. - BED, GFF & GTF covers coordinates and
bedtools.
Further reading
Section titled “Further reading”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.