Skip to content

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.

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
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

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:

Terminal window
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 TP53
chr2 24077431 24086839 - ENSG00000115129 TP53I3
chr17 43044295 43170245 - ENSG00000012048 BRCA1
chr13 32315474 32400266 + ENSG00000139618 BRCA2
chr7 55019017 55211628 + ENSG00000146648 EGFR
chr8 127735434 127742951 + ENSG00000136997 MYC
chr12 6534512 6538374 + ENSG00000111640 GAPDH
EOF

A sites-only VCF with six variants, one of them flagged LowQual:

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

A FASTA file with three records. The third one wraps over two lines:

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

Two 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:

Terminal window
mkdir -p data/run01 data/run02
cat > data/run01/sample_001.fastq <<'EOF'
@read_1
ACGTACGTACGT
+
IIIIIIIIIIII
@read_2
TTGACCGGTTAA
+
IIIIIIII####
@read_3
GGGCCCAAATTT
+
IIIIIIIIIIII
EOF
cat > data/run02/sample_002.fastq <<'EOF'
@read_1
CAGTCAGTCAGT
+
IIIIIIIIIIII
@read_2
ACGTTGCAACGT
+
@@@@IIIIIIII
EOF
: > data/run02/sample_003.fastq

A gzipped copy of the first run. -k keeps the uncompressed file next to it:

Terminal window
gzip -k data/run01/sample_001.fastq

A 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:

Terminal window
tr '|' '\t' > results.tsv <<'EOF'
gene|log2FC|padj
TP53|-1.8|3.2e-08
BRCA1|0.4|0.21
EGFR|2.6|1.5e-12
MYC|1.1|0.004
GAPDH|0.02|0.97
CDKN1A|3.1|2.0e-15
EOF
tr '|' '\t' > annotation.tsv <<'EOF'
gene|chrom|biotype
TP53|chr17|protein_coding
BRCA1|chr17|protein_coding
EGFR|chr7|protein_coding
MYC|chr8|protein_coding
CDKN1A|chr6|protein_coding
FOS|chr14|protein_coding
EOF
printf '%s\n' TP53 MYC CDKN1A > genes_of_interest.txt
printf '%s\n' CDKN1A EGFR TP53 MYC > deseq2_hits.txt
printf '%s\n' EGFR CDKN1A FOS TP53 > edger_hits.txt

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

A bare pattern matches anywhere in the line, so TP53 also finds TP53I3:

Terminal window
grep 'TP53' genes.gtf
chr17 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:

Terminal window
grep -w 'TP53' genes.gtf
chr17 HAVANA gene 7661779 7687538 . - . gene_id "ENSG00000141510"; gene_name "TP53";
Terminal window
grep -c '^>' sample.fa
3

-v inverts the match and -c counts what is left:

Terminal window
grep -vc '^#' sample.vcf
6
Terminal window
grep -E 'BRCA[12]' genes.gtf
chr17 HAVANA gene 43044295 43170245 . - . gene_id "ENSG00000012048"; gene_name "BRCA1";
chr13 HAVANA gene 32315474 32400266 . + . gene_id "ENSG00000139618"; gene_name "BRCA2";

The ##FILTER line that defines LowQual matches as well as the record that carries it:

Terminal window
grep -n 'LowQual' sample.vcf
4:##FILTER=<ID=LowQual,Description="QUAL below 30">
10:chr17 7675088 . C T 18 LowQual DP=6;AF=0.17

-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.

Terminal window
grep -A1 '^>seq2' sample.fa
>seq2 BRCA1 fragment
GATTTATCTGCTCTTCGCGTTGAAGAA
Terminal window
grep -o 'gene_name "[^"]*"' genes.gtf
gene_name "TP53"
gene_name "TP53I3"
gene_name "BRCA1"
gene_name "BRCA2"
gene_name "EGFR"
gene_name "MYC"
gene_name "GAPDH"

-F -f reads fixed strings from a file, and -w stops TP53 from matching TP53I3:

Terminal window
grep -wFf genes_of_interest.txt results.tsv
TP53 -1.8 3.2e-08
MYC 1.1 0.004
CDKN1A 3.1 2.0e-15

grep -r visits files in directory order, which differs between file systems. Sort the result when the order matters:

Terminal window
grep -r --include='*.fastq' '^@read_1' data | sort
data/run01/sample_001.fastq:@read_1
data/run02/sample_002.fastq:@read_1
Terminal window
grep -l 'GGGCCC' data/run01/*.fastq data/run02/*.fastq
data/run01/sample_001.fastq

zcat decompresses to the pipe and zgrep runs grep on the decompressed text. gzip -dc does the same job as zcat on any system.

Terminal window
zcat data/run01/sample_001.fastq.gz | head -n 4
@read_1
ACGTACGTACGT
+
IIIIIIIIIIII
Terminal window
zgrep -A1 '^@read_2' data/run01/sample_001.fastq.gz
@read_2
TTGACCGGTTAA

@ is also a quality character, Phred 31, so grep -c '^@' counts any quality line that starts with it. sample_002.fastq holds two reads:

Terminal window
grep -c '^@' data/run02/sample_002.fastq
3

Count lines and divide by four instead:

Terminal window
echo $(( $(wc -l < data/run02/sample_002.fastq) / 4 ))
2
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 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 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.

Terminal window
find data -name '*.fastq' | sort
data/run01/sample_001.fastq
data/run02/sample_002.fastq
data/run02/sample_003.fastq
Terminal window
find . -type d -name 'run*' | sort
./data/run01
./data/run02

A zero-byte FASTQ is the usual sign of a transfer or a demultiplexing step that failed:

Terminal window
find data -type f -empty
data/run02/sample_003.fastq
Terminal window
find . -name 'sample*' -not -path './data/*' | sort
./sample.fa
./sample.vcf

-exec ... {} + passes many files to one wc call, which is why a total line appears:

Terminal window
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 total

-print0 and read -d '' keep file names with spaces intact. sort -z sorts the NUL-separated list:

Terminal window
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 ))"
done
data/run01/sample_001.fastq 3 reads
data/run02/sample_002.fastq 2 reads
data/run02/sample_003.fastq 0 reads

-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.

Terminal window
find data -name '*.fastq' -print0 | xargs -0 -n1 -P2 md5sum | sort -k2
b90b1aedac887536f84370d4dea8154f data/run01/sample_001.fastq
fb44e00120e038ddfab566947e0dc6f7 data/run02/sample_002.fastq
d41d8cd98f00b204e9800998ecf8427e data/run02/sample_003.fastq

A 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
Terminal window
grep -v '^#' genes.gtf | cut -f1 | sort -u
chr12
chr13
chr17
chr2
chr7
chr8

Plain sort puts chr12 before chr2. sort -V compares the numbers inside the names:

Terminal window
grep -v '^#' genes.gtf | cut -f1 | sort -uV
chr2
chr7
chr8
chr12
chr13
chr17

uniq -c counts runs of identical lines, so it needs sorted input:

Terminal window
grep -v '^#' sample.vcf | cut -f1 | sort | uniq -c
1 chr1
1 chr13
3 chr17
1 chr7
Terminal window
grep -v '^#' sample.vcf | cut -f7 | sort | uniq -c | sort -k1,1nr
5 PASS
1 LowQual

sort -n does not read scientific notation. It takes 1.5e-12 as 1.5 and puts the strongest hits last:

Terminal window
tail -n +2 results.tsv | sort -t$'\t' -k3,3n
MYC 1.1 0.004
BRCA1 0.4 0.21
GAPDH 0.02 0.97
EGFR 2.6 1.5e-12
CDKN1A 3.1 2.0e-15
TP53 -1.8 3.2e-08

sort -g parses the exponent:

Terminal window
tail -n +2 results.tsv | sort -t$'\t' -k3,3g | head -n 3
CDKN1A 3.1 2.0e-15
EGFR 2.6 1.5e-12
TP53 -1.8 3.2e-08

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:

Terminal window
comm -12 <(sort deseq2_hits.txt) <(sort edger_hits.txt)
CDKN1A
EGFR
TP53

comm -23 keeps the lines only in the first file and comm -13 the lines only in the second.

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:

Terminal window
paste deseq2_hits.txt edger_hits.txt
CDKN1A EGFR
EGFR CDKN1A
TP53 FOS
MYC TP53

Each - 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:

Terminal window
paste - - - - < data/run01/sample_001.fastq
@read_1 ACGTACGTACGT + IIIIIIIIIIII
@read_2 TTGACCGGTTAA + IIIIIIII####
@read_3 GGGCCCAAATTT + IIIIIIIIIIII

join matches lines on their first field, and both inputs must be sorted on that field. Drop the header lines and sort first:

Terminal window
tail -n +2 results.tsv | sort -t $'\t' -k1,1 > results_sorted.tsv
tail -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:

Terminal window
join -t $'\t' results_sorted.tsv annotation_sorted.tsv
BRCA1 0.4 0.21 chr17 protein_coding
CDKN1A 3.1 2.0e-15 chr6 protein_coding
EGFR 2.6 1.5e-12 chr7 protein_coding
MYC 1.1 0.004 chr8 protein_coding
TP53 -1.8 3.2e-08 chr17 protein_coding

GAPDH 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.

Terminal window
join -t $'\t' -a 1 -e NA -o auto results_sorted.tsv annotation_sorted.tsv
BRCA1 0.4 0.21 chr17 protein_coding
CDKN1A 3.1 2.0e-15 chr6 protein_coding
EGFR 2.6 1.5e-12 chr7 protein_coding
GAPDH 0.02 0.97 NA NA
MYC 1.1 0.004 chr8 protein_coding
TP53 -1.8 3.2e-08 chr17 protein_coding

Run 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.

tee writes its input to a file and passes it on down the pipe:

Terminal window
grep -v '^#' sample.vcf | tee variants_body.tsv | wc -l
6
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

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.

Terminal window
grep -c '^>' sample.fa missing.fa > counts.txt 2> errors.log || true
cat counts.txt errors.log
sample.fa:3
grep: missing.fa: No such file or directory
Terminal window
printf 'sample_001\tdone\n' >> run.log
printf 'sample_002\tdone\n' >> run.log
cat run.log
sample_001 done
sample_002 done

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:

Terminal window
grep 'chrZ' sample.vcf | wc -l
echo "stages: ${PIPESTATUS[*]}"
0
stages: 1 0

set -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:

Terminal window
status=0
(set -o pipefail; grep 'chrZ' sample.vcf | wc -l) || status=$?
echo "pipeline status with pipefail: $status"
0
pipeline status with pipefail: 1

Start 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.

  • 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.

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.