grep, find & pipes
grep searches text for a pattern, find walks a directory tree, and the pipe operator |
hands the output of one command to the next. Together with sort, cut, uniq, and wc
they answer most “how many” and “which ones” questions about a sequencing project without a
script. Every command below ran with GNU grep 3.11 and GNU findutils 4.9 in the page’s container.
Quick reference
Section titled “Quick reference”| Task | Command |
|---|---|
| Find a pattern | grep 'pattern' file |
| Ignore case | grep -i 'pattern' file |
| Invert | grep -v 'pattern' file |
| Count | grep -c 'pattern' file |
| Whole word | grep -w 'TP53' file |
| Several patterns | grep -E 'BRCA1|BRCA2' file |
| Patterns from a file | grep -wFf genes.txt table.tsv |
| Only the match | grep -o 'pattern' file |
| Context | grep -B2 -A2 'pattern' file |
| Recursive by glob | grep -r --include='*.vcf' 'pattern' dir/ |
| Files with a match | grep -l 'pattern' *.fastq |
| Gzipped input | zgrep 'pattern' file.gz |
| Task | Command |
|---|---|
| By name | find . -name '*.bam' |
| By type | find . -type f or -type d |
| By size | find . -size +1G |
| Empty files | find . -type f -empty |
| Recently modified | find . -mtime -7 |
| Exclude a path | find . -not -path './tmp/*' |
| Limit depth | find . -maxdepth 2 -name '*.txt' |
| Run once per file | find . -name '*.bam' -exec samtools index {} \; |
| Parallel | find . -name '*.bam' -print0 | xargs -0 -n1 -P4 samtools index |
Pipe patterns
Section titled “Pipe patterns”| Goal | Pipeline |
|---|---|
| Top N by a numeric column | sort -t$'\t' -k3,3g file | head -n N |
| Unique values | cut -f1 file | sort -u |
| Frequency table | cut -f1 file | sort | uniq -c | sort -k1,1nr |
| Skip the header | tail -n +2 file |
| Lines in both lists | comm -12 <(sort a) <(sort b) |
| Files side by side | paste a.txt b.txt |
| One FASTQ record per line | paste - - - - < file.fq |
| Lines as one comma list | paste -sd, file |
| Join on the first column | join -t $'\t' <(sort a.tsv) <(sort b.tsv) |
| Duplicated values | cut -f1 file | sort | uniq -d |
Example files
Section titled “Example files”Paste these blocks into an empty directory to follow along. The tables use | between
columns and tr turns each one into a tab, so the files keep their tabs after a copy from the
browser.
A seven-gene GTF. GTF lines are long, so awk builds the nine columns from a short table:
awk -v OFS='\t' 'BEGIN {print "#!genome-build GRCh38"} { attributes = "gene_id \"" $5 "\"; gene_name \"" $6 "\";" print $1, "HAVANA", "gene", $2, $3, ".", $4, ".", attributes }' > genes.gtf <<'EOF'chr17 7661779 7687538 - ENSG00000141510 TP53chr2 24077431 24086839 - ENSG00000115129 TP53I3chr17 43044295 43170245 - ENSG00000012048 BRCA1chr13 32315474 32400266 + ENSG00000139618 BRCA2chr7 55019017 55211628 + ENSG00000146648 EGFRchr8 127735434 127742951 + ENSG00000136997 MYCchr12 6534512 6538374 + ENSG00000111640 GAPDHEOFA sites-only VCF with six variants, one of them flagged LowQual:
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=40EOFA FASTA file with three records. The third one wraps over two lines:
cat > sample.fa <<'EOF'>seq1 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq2 BRCA1 fragmentGATTTATCTGCTCTTCGCGTTGAAGAA>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCEOFTwo sequencing runs of FASTQ files. The second read in sample_002.fastq has a quality line
that starts with @, which is legal, and sample_003.fastq is empty, the way a failed transfer
leaves a file:
mkdir -p data/run01 data/run02cat > data/run01/sample_001.fastq <<'EOF'@read_1ACGTACGTACGT+IIIIIIIIIIII@read_2TTGACCGGTTAA+IIIIIIII####@read_3GGGCCCAAATTT+IIIIIIIIIIIIEOFcat > data/run02/sample_002.fastq <<'EOF'@read_1CAGTCAGTCAGT+IIIIIIIIIIII@read_2ACGTTGCAACGT+@@@@IIIIIIIIEOF: > data/run02/sample_003.fastqA gzipped copy of the first run. -k keeps the uncompressed file next to it:
gzip -k data/run01/sample_001.fastqA differential expression table, a gene annotation table, and three gene lists. The annotation
has no row for GAPDH and adds FOS, which has no result:
tr '|' '\t' > results.tsv <<'EOF'gene|log2FC|padjTP53|-1.8|3.2e-08BRCA1|0.4|0.21EGFR|2.6|1.5e-12MYC|1.1|0.004GAPDH|0.02|0.97CDKN1A|3.1|2.0e-15EOFtr '|' '\t' > annotation.tsv <<'EOF'gene|chrom|biotypeTP53|chr17|protein_codingBRCA1|chr17|protein_codingEGFR|chr7|protein_codingMYC|chr8|protein_codingCDKN1A|chr6|protein_codingFOS|chr14|protein_codingEOFprintf '%s\n' TP53 MYC CDKN1A > genes_of_interest.txtprintf '%s\n' CDKN1A EGFR TP53 MYC > deseq2_hits.txtprintf '%s\n' EGFR CDKN1A FOS TP53 > edger_hits.txtgrep basics
Section titled “grep basics”The pattern is a basic regular expression unless you pass -E for extended regex or -F for a
fixed string.
| Flag | What it does |
|---|---|
-i |
Ignore case |
-v |
Print the lines that do not match |
-c |
Count matching lines instead of printing them |
-n |
Prefix each line with its line number |
-l |
Print only the names of files with a match |
-L |
Print only the names of files without a match |
-r |
Search a directory recursively |
-w |
Match whole words only |
-x |
Match whole lines only |
-A N, -B N, -C N |
Print N lines after, before, or around each match |
-o |
Print only the matched part of the line |
-E |
Extended regex, so +, ?, |, and () need no backslash |
-F |
Fixed string, no regex at all |
-f FILE |
Read one pattern per line from FILE |
--include='*.fastq' |
Limit a recursive search to matching file names |
--exclude-dir='.git' |
Skip a directory in a recursive search |
grep recipes
Section titled “grep recipes”Find a gene, then match the whole word
Section titled “Find a gene, then match the whole word”A bare pattern matches anywhere in the line, so TP53 also finds TP53I3:
grep 'TP53' genes.gtfchr17 HAVANA gene 7661779 7687538 . - . gene_id "ENSG00000141510"; gene_name "TP53";chr2 HAVANA gene 24077431 24086839 . - . gene_id "ENSG00000115129"; gene_name "TP53I3";-w requires a non-word character on both sides of the match:
grep -w 'TP53' genes.gtfchr17 HAVANA gene 7661779 7687538 . - . gene_id "ENSG00000141510"; gene_name "TP53";Count FASTA records
Section titled “Count FASTA records”grep -c '^>' sample.fa3Count VCF records without the header
Section titled “Count VCF records without the header”-v inverts the match and -c counts what is left:
grep -vc '^#' sample.vcf6Match one of several patterns
Section titled “Match one of several patterns”grep -E 'BRCA[12]' genes.gtfchr17 HAVANA gene 43044295 43170245 . - . gene_id "ENSG00000012048"; gene_name "BRCA1";chr13 HAVANA gene 32315474 32400266 . + . gene_id "ENSG00000139618"; gene_name "BRCA2";Show line numbers
Section titled “Show line numbers”The ##FILTER line that defines LowQual matches as well as the record that carries it:
grep -n 'LowQual' sample.vcf4:##FILTER=<ID=LowQual,Description="QUAL below 30">10:chr17 7675088 . C T 18 LowQual DP=6;AF=0.17Print the line after a match
Section titled “Print the line after a match”-A1 prints one line of context after each header. That gives the full sequence only when
each record sits on one line; seq3 would lose its second line, and the
awk cheatsheet has a recipe for wrapped records.
grep -A1 '^>seq2' sample.fa>seq2 BRCA1 fragmentGATTTATCTGCTCTTCGCGTTGAAGAAPrint only the matched text
Section titled “Print only the matched text”grep -o 'gene_name "[^"]*"' genes.gtfgene_name "TP53"gene_name "TP53I3"gene_name "BRCA1"gene_name "BRCA2"gene_name "EGFR"gene_name "MYC"gene_name "GAPDH"Filter a table by a list of genes
Section titled “Filter a table by a list of genes”-F -f reads fixed strings from a file, and -w stops TP53 from matching TP53I3:
grep -wFf genes_of_interest.txt results.tsvTP53 -1.8 3.2e-08MYC 1.1 0.004CDKN1A 3.1 2.0e-15Search a directory tree
Section titled “Search a directory tree”grep -r visits files in directory order, which differs between file systems. Sort the result
when the order matters:
grep -r --include='*.fastq' '^@read_1' data | sortdata/run01/sample_001.fastq:@read_1data/run02/sample_002.fastq:@read_1List the files that match
Section titled “List the files that match”grep -l 'GGGCCC' data/run01/*.fastq data/run02/*.fastqdata/run01/sample_001.fastqSearch a gzipped file
Section titled “Search a gzipped file”zcat decompresses to the pipe and zgrep runs grep on the decompressed text. gzip -dc does
the same job as zcat on any system.
zcat data/run01/sample_001.fastq.gz | head -n 4@read_1ACGTACGTACGT+IIIIIIIIIIIIzgrep -A1 '^@read_2' data/run01/sample_001.fastq.gz@read_2TTGACCGGTTAADo not count FASTQ reads with grep
Section titled “Do not count FASTQ reads with grep”@ is also a quality character, Phred 31, so grep -c '^@' counts any quality line that
starts with it. sample_002.fastq holds two reads:
grep -c '^@' data/run02/sample_002.fastq3Count lines and divide by four instead:
echo $(( $(wc -l < data/run02/sample_002.fastq) / 4 ))2Common regex patterns
Section titled “Common regex patterns”| Pattern | Meaning |
|---|---|
^> |
Line starts with >, a FASTA header |
^# |
Line starts with #, a VCF or GTF header |
chr[0-9]+ |
chr followed by digits, with -E |
BRCA[12] |
BRCA1 or BRCA2 |
\bTP53\b |
TP53 as a whole word, the same as -w |
^[ACGTN]+$ |
A line of DNA bases only, with -E |
gene_name "[^"]*" |
The full gene_name attribute in a GTF |
GNU grep also accepts -P for Perl syntax such as \d, \s, and lookaheads. The grep that
ships with macOS does not support -P. ripgrep, run as rg, is a faster recursive search
that uses Rust regex by default.
find basics
Section titled “find basics”find walks a directory tree and tests each entry against your conditions.
| Test or action | What it does |
|---|---|
-name '*.bam' |
Match the file name with a glob; quote the glob |
-iname '*.BAM' |
The same, ignoring case |
-type f, -type d, -type l |
Files, directories, or symlinks |
-size +1G |
Larger than 1 GiB; also +100M, -1k |
-empty |
Empty files and directories |
-mtime -7 |
Modified in the last 7 days |
-newer FILE |
Modified more recently than FILE |
-path '*/run01/*' |
Match the whole path with a glob |
-not TEST |
Negate a test |
-maxdepth 2 |
Descend at most two levels |
-exec cmd {} \; |
Run a command once per match |
-exec cmd {} + |
Run a command on many matches at once |
-print0 |
Separate results with NUL for xargs -0 |
find recipes
Section titled “find recipes”find prints entries in directory order, which is not alphabetical and differs between
machines. Pipe the result through sort whenever more than one file can match.
Find files by name
Section titled “Find files by name”find data -name '*.fastq' | sortdata/run01/sample_001.fastqdata/run02/sample_002.fastqdata/run02/sample_003.fastqFind directories
Section titled “Find directories”find . -type d -name 'run*' | sort./data/run01./data/run02Find empty files
Section titled “Find empty files”A zero-byte FASTQ is the usual sign of a transfer or a demultiplexing step that failed:
find data -type f -emptydata/run02/sample_003.fastqExclude a subtree
Section titled “Exclude a subtree”find . -name 'sample*' -not -path './data/*' | sort./sample.fa./sample.vcfRun one command on all matches
Section titled “Run one command on all matches”-exec ... {} + passes many files to one wc call, which is why a total line appears:
find data -name '*.fastq' -exec wc -l {} + | sort -k2 12 data/run01/sample_001.fastq 8 data/run02/sample_002.fastq 0 data/run02/sample_003.fastq 20 totalLoop over matches safely
Section titled “Loop over matches safely”-print0 and read -d '' keep file names with spaces intact. sort -z sorts the NUL-separated
list:
find data -name '*.fastq' -print0 | sort -z | while IFS= read -r -d '' fq; do printf '%s\t%d reads\n' "$fq" "$(( $(wc -l < "$fq") / 4 ))" donedata/run01/sample_001.fastq 3 readsdata/run02/sample_002.fastq 2 readsdata/run02/sample_003.fastq 0 readsRun in parallel with xargs
Section titled “Run in parallel with xargs”-P2 runs two md5sum processes at once and -n1 gives each one file. Parallel jobs finish in
any order, so sort the result. On macOS the command is md5 -r.
find data -name '*.fastq' -print0 | xargs -0 -n1 -P2 md5sum | sort -k2b90b1aedac887536f84370d4dea8154f data/run01/sample_001.fastqfb44e00120e038ddfab566947e0dc6f7 data/run02/sample_002.fastqd41d8cd98f00b204e9800998ecf8427e data/run02/sample_003.fastqA pipe sends the standard output of one command to the standard input of the next. Most one-liners filter rows, pick columns, then sort and count.
| Step | Tool |
|---|---|
| Filter rows | grep, awk '/pattern/' |
| Pick columns | cut -f, awk '{print $N}' |
| Sort | sort, with -k for a column, -n or -g for numbers, -r to reverse |
| Count or drop duplicates | uniq -c, uniq, sort -u |
| Take a slice | head -n N, tail -n +2 |
| Count lines | wc -l |
| Substitute | sed, tr |
| Combine files | paste, join, comm |
Unique chromosomes
Section titled “Unique chromosomes”grep -v '^#' genes.gtf | cut -f1 | sort -uchr12chr13chr17chr2chr7chr8Plain sort puts chr12 before chr2. sort -V compares the numbers inside the names:
grep -v '^#' genes.gtf | cut -f1 | sort -uVchr2chr7chr8chr12chr13chr17Variants per chromosome
Section titled “Variants per chromosome”uniq -c counts runs of identical lines, so it needs sorted input:
grep -v '^#' sample.vcf | cut -f1 | sort | uniq -c 1 chr1 1 chr13 3 chr17 1 chr7Records per FILTER value
Section titled “Records per FILTER value”grep -v '^#' sample.vcf | cut -f7 | sort | uniq -c | sort -k1,1nr 5 PASS 1 LowQualSort by p-value
Section titled “Sort by p-value”sort -n does not read scientific notation. It takes 1.5e-12 as 1.5 and puts the strongest
hits last:
tail -n +2 results.tsv | sort -t$'\t' -k3,3nMYC 1.1 0.004BRCA1 0.4 0.21GAPDH 0.02 0.97EGFR 2.6 1.5e-12CDKN1A 3.1 2.0e-15TP53 -1.8 3.2e-08sort -g parses the exponent:
tail -n +2 results.tsv | sort -t$'\t' -k3,3g | head -n 3CDKN1A 3.1 2.0e-15EGFR 2.6 1.5e-12TP53 -1.8 3.2e-08Compare two gene lists
Section titled “Compare two gene lists”comm needs sorted input, and <(...) passes the output of a command where a file name is
expected. -12 keeps the lines found in both files:
comm -12 <(sort deseq2_hits.txt) <(sort edger_hits.txt)CDKN1AEGFRTP53comm -23 keeps the lines only in the first file and comm -13 the lines only in the second.
Put files side by side
Section titled “Put files side by side”paste joins line 1 of each file, then line 2, and so on, with a tab between them. It does not
match keys, so the files must already be in the same order:
paste deseq2_hits.txt edger_hits.txtCDKN1A EGFREGFR CDKN1ATP53 FOSMYC TP53Each - reads the next line from standard input, so paste - - - - puts each four-line FASTQ
record on one tab-separated line, ready for cut, sort, or awk:
paste - - - - < data/run01/sample_001.fastq@read_1 ACGTACGTACGT + IIIIIIIIIIII@read_2 TTGACCGGTTAA + IIIIIIII####@read_3 GGGCCCAAATTT + IIIIIIIIIIIIJoin two tables on a key
Section titled “Join two tables on a key”join matches lines on their first field, and both inputs must be sorted on that field. Drop
the header lines and sort first:
tail -n +2 results.tsv | sort -t $'\t' -k1,1 > results_sorted.tsvtail -n +2 annotation.tsv | sort -t $'\t' -k1,1 > annotation_sorted.tsv-t $'\t' splits on tabs and writes tabs. Without it, join splits on runs of blanks and
writes a space between the fields:
join -t $'\t' results_sorted.tsv annotation_sorted.tsvBRCA1 0.4 0.21 chr17 protein_codingCDKN1A 3.1 2.0e-15 chr6 protein_codingEGFR 2.6 1.5e-12 chr7 protein_codingMYC 1.1 0.004 chr8 protein_codingTP53 -1.8 3.2e-08 chr17 protein_codingGAPDH and FOS each appear in one table only, so join drops them. -a 1 keeps the
unmatched lines of the first file, and -e NA -o auto fills their empty fields. -o auto is
a GNU option.
join -t $'\t' -a 1 -e NA -o auto results_sorted.tsv annotation_sorted.tsvBRCA1 0.4 0.21 chr17 protein_codingCDKN1A 3.1 2.0e-15 chr6 protein_codingEGFR 2.6 1.5e-12 chr7 protein_codingGAPDH 0.02 0.97 NA NAMYC 1.1 0.004 chr8 protein_codingTP53 -1.8 3.2e-08 chr17 protein_codingRun sort and join under the same locale. Prefix both with LC_ALL=C in a script, so a
change of locale between the two steps cannot break the order that join expects.
Save an intermediate step
Section titled “Save an intermediate step”tee writes its input to a file and passes it on down the pipe:
grep -v '^#' sample.vcf | tee variants_body.tsv | wc -l6Redirection
Section titled “Redirection”| Symbol | What it does |
|---|---|
> |
Write stdout to a file, replacing it |
>> |
Append stdout to a file |
< |
Read stdin from a file |
2> |
Write stderr to a file |
2>&1 |
Send stderr to wherever stdout goes |
&> |
Send stdout and stderr to one file |
| |
Pipe stdout into the next command |
|& |
Pipe stdout and stderr together |
cmd1 && cmd2 |
Run cmd2 only if cmd1 succeeds |
cmd1 || cmd2 |
Run cmd2 only if cmd1 fails |
Split results and errors
Section titled “Split results and errors”missing.fa does not exist, so grep writes a count for sample.fa to stdout and an error to
stderr, then exits with status 2. The || true keeps this page’s script running past that
intended failure; leave it out of a real pipeline.
grep -c '^>' sample.fa missing.fa > counts.txt 2> errors.log || truecat counts.txt errors.logsample.fa:3grep: missing.fa: No such file or directoryAppend to a log
Section titled “Append to a log”printf 'sample_001\tdone\n' >> run.logprintf 'sample_002\tdone\n' >> run.logcat run.logsample_001 donesample_002 donepipefail
Section titled “pipefail”A pipeline returns the exit status of its last command. Here grep finds nothing on chrZ and
fails, but wc -l succeeds, so the pipeline reports success. PIPESTATUS holds the status of
every stage:
grep 'chrZ' sample.vcf | wc -lecho "stages: ${PIPESTATUS[*]}"0stages: 1 0set -o pipefail makes the pipeline fail when any stage fails. The subshell keeps the setting
local to this block, and || status=$? records the failure instead of stopping the script:
status=0(set -o pipefail; grep 'chrZ' sample.vcf | wc -l) || status=$?echo "pipeline status with pipefail: $status"0pipeline status with pipefail: 1Start a production script with set -euo pipefail. Expect grep with no match and head
closing a pipe early to stop such a script, and handle both on purpose.
See also
Section titled “See also”- awk for per-column logic, sums, and group counts.
- sed for substitution and line edits.
- Pipes & Redirection explains streams,
tee, and exit codes from the start. - Text Processing teaches grep, cut, sort, and uniq step by step.
- Shell Scripts covers loops, exit codes, and
set -euo pipefail. - Inspecting Files collects the checks to run on a new FASTQ, BAM, or VCF.
Further reading
Section titled “Further reading”The GNU grep manual distinguishes fixed strings, regular expressions, selected lines, and individual matches. These distinctions explain the gene filters and the FASTQ count counterexample.
The GNU Findutils 4.9.0 manual describes path tests, command execution, and NUL-separated filenames. Its safe filename section explains the find and xargs recipes.
The GNU sort reference distinguishes numeric and general numeric order. The Bash set reference defines pipefail and the exceptions to errexit, which determine how these command chains report failures.