Skip to content

sed

sed reads its input one line at a time, applies a short script of edits, and prints each line. In bioinformatics it renames chromosomes, cleans FASTA headers, rewrites paths in sample sheets, and drops header or blank lines. For anything that counts or does arithmetic on columns, use awk.

The examples ran with GNU sed 4.9. macOS ships BSD sed, and the recipes that need a GNU feature say so. The table at the end of the page lists those differences.

Task One-liner
Replace the first match on each line sed 's/old/new/' file
Replace every match sed 's/old/new/g' file
Capture groups sed -E 's/(chr)([0-9]+)/\2_\1/' file
Path-safe delimiter sed 's|/old/dir|/new/dir|g' file
Shell variable sed "s/${old}/${new}/g" file
Several edits sed -e 's/a/b/' -e 's/c/d/' file
In place with backup sed -i.bak 's/old/new/g' file
Delete the header sed '1d' file
Delete the last line sed '$d' file
Delete blank lines sed '/^[[:space:]]*$/d' file
Delete comment lines sed '/^#/d' file
Print a range sed -n '10,20p' file
Print line N sed -n "${n}p" file
Print the first N lines sed 10q file
Print matching lines sed -n '/^>/p' file.fa
FASTQ sequence lines, GNU sed -n '2~4p' file.fq
Edit all lines but headers sed '/^#/!s/old/new/' file
Trim FASTA headers to the ID sed '/^>/s/ .*//' file.fa
Strip chr from VCF records sed '/^#/!s/^chr//' file.vcf
Windows line endings sed 's/\r$//' file
Complement bases sed 'y/ACGT/TGCA/' file

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.

An unsorted BED file and a long-format count table:

Terminal window
tr '|' '\t' > regions.bed <<'EOF'
chr2|100|200|peak1
chr1|50|150|peak2
chr1|300|400|peak3
chr3|500|700|peak4
EOF
tr '|' '\t' > counts.tsv <<'EOF'
gene|sample|count
TP53|ctrl_1|120
TP53|trt_1|98
BRCA1|ctrl_1|45
BRCA1|trt_1|60
EOF

A VCF whose header declares its contigs with the chr prefix:

Terminal window
tr '|' '\t' > sample.vcf <<'EOF'
##fileformat=VCFv4.2
##contig=<ID=chr1,length=248956422>
##contig=<ID=chr7,length=159345973>
##contig=<ID=chr13,length=114364328>
##contig=<ID=chr17,length=83257441>
##FILTER=<ID=LowQual,Description="QUAL below 30">
#CHROM|POS|ID|REF|ALT|QUAL|FILTER|INFO
chr1|14653|.|C|T|100|PASS|.
chr7|55191822|.|T|G|210|PASS|.
chr13|32316000|.|G|A|250|PASS|.
chr17|7675088|.|C|T|18|LowQual|.
EOF

A FASTA file with descriptions in the headers and a soft-masked, lowercase stretch in seq2:

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

A sample sheet with absolute paths, a list of sample names, a file with runs of spaces, and a CSV with the \r\n line endings that Windows spreadsheet programs write:

Terminal window
cat > samplesheet.csv <<'EOF'
sample,fastq_1,fastq_2
ctrl_1,/data/run01/ctrl_1_R1.fastq.gz,/data/run01/ctrl_1_R2.fastq.gz
trt_1,/data/run01/trt_1_R1.fastq.gz,/data/run01/trt_1_R2.fastq.gz
EOF
printf '%s\n' ctrl_1 ctrl_2 trt_1 trt_2 > samples.txt
printf 'TP53 120\nMYC 30\n' > messy.txt
printf '%s\r\n' 'sample,condition' 'ctrl_1,control' 'trt_1,treated' \
> from_excel.csv

s/pattern/replacement/ replaces the first match on each line. A g flag replaces every match and a number replaces only that occurrence:

Terminal window
echo 'chr1,chr2,chr3' | sed 's/chr//'
echo 'chr1,chr2,chr3' | sed 's/chr//g'
echo 'chr1,chr2,chr3' | sed 's/chr//2'
1,chr2,chr3
1,2,3
chr1,2,chr3

-E turns on extended regex, so ( ) and + need no backslash. \1 and \2 refer back to the groups:

Terminal window
sed -E 's/^>(seq[0-9]+) ([A-Z0-9]+) .*/>\2|\1/' sample.fa
>TP53|seq1
ATGGAGGAGCCGCAGTCAGATCCTAGC
>BRCA1|seq2
GATTTATCTGctcttcgcgTTGAAGAA
>EGFR|seq3
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC

& in the replacement stands for the text the pattern matched:

Terminal window
sed 's/^>seq[0-9]*/&_GRCh38/' sample.fa
>seq1_GRCh38 TP53 fragment
ATGGAGGAGCCGCAGTCAGATCCTAGC
>seq2_GRCh38 BRCA1 fragment
GATTTATCTGctcttcgcgTTGAAGAA
>seq3_GRCh38 EGFR fragment
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC

Any character after s becomes the delimiter, so a path needs no escaped slashes:

Terminal window
sed 's|/data/run01/|/scratch/project/fastq/|g' samplesheet.csv
sample,fastq_1,fastq_2
ctrl_1,/scratch/project/fastq/ctrl_1_R1.fastq.gz,/scratch/project/fastq/ctrl_1_R2.fastq.gz
trt_1,/scratch/project/fastq/trt_1_R1.fastq.gz,/scratch/project/fastq/trt_1_R2.fastq.gz

Put the script in double quotes so the shell expands the variable before sed sees it. If the value can contain a /, use | as the delimiter:

Terminal window
old_run=run01
new_run=run02
sed "s/${old_run}/${new_run}/g" samplesheet.csv
sample,fastq_1,fastq_2
ctrl_1,/data/run02/ctrl_1_R1.fastq.gz,/data/run02/ctrl_1_R2.fastq.gz
trt_1,/data/run02/trt_1_R1.fastq.gz,/data/run02/trt_1_R2.fastq.gz
Terminal window
sed -e 's/^>seq/>contig_/' -e 's/ fragment$//' sample.fa
>contig_1 TP53
ATGGAGGAGCCGCAGTCAGATCCTAGC
>contig_2 BRCA1
GATTTATCTGctcttcgcgTTGAAGAA
>contig_3 EGFR
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC

-i.bak edits the file and keeps the original as regions_edit.bed.bak. Practice on a copy first:

Terminal window
cp regions.bed regions_edit.bed
sed -i.bak 's/^chr//' regions_edit.bed
head -n 2 regions_edit.bed regions_edit.bed.bak
==> regions_edit.bed <==
2 100 200 peak1
1 50 150 peak2
==> regions_edit.bed.bak <==
chr2 100 200 peak1
chr1 50 150 peak2

GNU sed also accepts -i with no suffix. BSD sed on macOS needs -i '' for that, so -i.bak is the spelling that works on both.

/^#/! applies the substitution to every line that does not start with #:

Terminal window
sed '/^#/!s/^chr//' sample.vcf
##fileformat=VCFv4.2
##contig=<ID=chr1,length=248956422>
##contig=<ID=chr7,length=159345973>
##contig=<ID=chr13,length=114364328>
##contig=<ID=chr17,length=83257441>
##FILTER=<ID=LowQual,Description="QUAL below 30">
#CHROM POS ID REF ALT QUAL FILTER INFO
1 14653 . C T 100 PASS .
7 55191822 . T G 210 PASS .
13 32316000 . G A 250 PASS .
17 7675088 . C T 18 LowQual .

The records now say 1 and 17, while the ##contig lines still declare chr1 and chr17, so the header and the body disagree.

Terminal window
sed -E -e '/^#/!s/^chr//' -e 's/^(##contig=<ID=)chr/\1/' sample.vcf \
> nochr.vcf
cat nochr.vcf
##fileformat=VCFv4.2
##contig=<ID=1,length=248956422>
##contig=<ID=7,length=159345973>
##contig=<ID=13,length=114364328>
##contig=<ID=17,length=83257441>
##FILTER=<ID=LowQual,Description="QUAL below 30">
#CHROM POS ID REF ALT QUAL FILTER INFO
1 14653 . C T 100 PASS .
7 55191822 . T G 210 PASS .
13 32316000 . G A 250 PASS .
17 7675088 . C T 18 LowQual .

bcftools annotate --rename-chrs map.txt renames both parts from a two-column mapping file and is the safer tool for a real VCF.

Terminal window
sed -E -e '/^#/!s/^/chr/' -e 's/^(##contig=<ID=)/\1chr/' nochr.vcf
##fileformat=VCFv4.2
##contig=<ID=chr1,length=248956422>
##contig=<ID=chr7,length=159345973>
##contig=<ID=chr13,length=114364328>
##contig=<ID=chr17,length=83257441>
##FILTER=<ID=LowQual,Description="QUAL below 30">
#CHROM POS ID REF ALT QUAL FILTER INFO
chr1 14653 . C T 100 PASS .
chr7 55191822 . T G 210 PASS .
chr13 32316000 . G A 250 PASS .
chr17 7675088 . C T 18 LowQual .

Many tools stop reading a header at the first space. The /^>/ address keeps sequence lines out of the edit:

Terminal window
sed '/^>/s/ .*//' sample.fa
>seq1
ATGGAGGAGCCGCAGTCAGATCCTAGC
>seq2
GATTTATCTGctcttcgcgTTGAAGAA
>seq3
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC

-n turns off the automatic print and p prints the lines that match:

Terminal window
sed -n '/^>/p' sample.fa
>seq1 TP53 fragment
>seq2 BRCA1 fragment
>seq3 EGFR fragment

\U is a GNU extension. On macOS use awk '!/^>/ {$0 = toupper($0)} 1' instead.

Terminal window
sed '/^>/!s/.*/\U&/' sample.fa
>seq1 TP53 fragment
ATGGAGGAGCCGCAGTCAGATCCTAGC
>seq2 BRCA1 fragment
GATTTATCTGCTCTTCGCGTTGAAGAA
>seq3 EGFR fragment
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC

The range /^>seq2 /,/^>/ runs from the seq2 header to the next header. Inside it, sed deletes the seq2 header and every sequence line, and keeps the next header. The space after the ID stops the pattern from matching seq20.

Terminal window
sed '/^>seq2 /,/^>/{/^>seq2 /d;/^>/!d;}' sample.fa
>seq1 TP53 fragment
ATGGAGGAGCCGCAGTCAGATCCTAGC
>seq3 EGFR fragment
ATGCGACCCTCCGGGACGGCCGGGGCA
GCGCTCCTGGCGCTGCTGGCTGCGCTC

seqkit grep -v -p seq2 matches the ID exactly and is the tool for large files.

y maps characters one to one, like tr. It gives the complement, and rev reverses it:

Terminal window
echo 'ATGAAACCC' | sed 'y/ACGT/TGCA/'
echo 'ATGAAACCC' | sed 'y/ACGT/TGCA/' | rev
TACTTTGGG
GGGTTTCAT
Terminal window
sed '1d' counts.tsv
TP53 ctrl_1 120
TP53 trt_1 98
BRCA1 ctrl_1 45
BRCA1 trt_1 60

The one-line form of i and the \t escape are GNU extensions:

Terminal window
sed '1i chrom\tstart\tend\tname' regions.bed
chrom start end name
chr2 100 200 peak1
chr1 50 150 peak2
chr1 300 400 peak3
chr3 500 700 peak4

cat -A makes the result visible: a tab prints as ^I and each line end as $. \t in the replacement is GNU only; on macOS use awk -v OFS='\t' '{$1 = $1} 1'.

Terminal window
sed -E 's/ +/\t/g' messy.txt | cat -A
TP53^I120$
MYC^I30$

The ^M before each $ is the carriage return that breaks column matching and sample names:

Terminal window
cat -A from_excel.csv
sample,condition^M$
ctrl_1,control^M$
trt_1,treated^M$
Terminal window
sed 's/\r$//' from_excel.csv | cat -A
sample,condition$
ctrl_1,control$
trt_1,treated$

\r in a pattern is GNU only. tr -d '\r' works everywhere.

Terminal window
printf 'TP53\n\nMYC\n \nEGFR\n' | sed '/^[[:space:]]*$/d'
TP53
MYC
EGFR
Terminal window
sed '/^#/d' sample.vcf
chr1 14653 . C T 100 PASS .
chr7 55191822 . T G 210 PASS .
chr13 32316000 . G A 250 PASS .
chr17 7675088 . C T 18 LowQual .

An address limits a command to some lines. It can be a line number, $ for the last line, a regex, or a range of two of these. ! after the address negates it.

Terminal window
sed -n '2,4p' counts.tsv
TP53 ctrl_1 120
TP53 trt_1 98
BRCA1 ctrl_1 45

This is how a SLURM array task picks its sample, with the task ID in place of task_id:

Terminal window
task_id=3
sed -n "${task_id}p" samples.txt
trt_1

3q prints three lines and exits, so sed does not read the rest of a large file:

Terminal window
sed 3q counts.tsv
gene sample count
TP53 ctrl_1 120
TP53 trt_1 98
Terminal window
sed '/^#/!s/PASS/QC_OK/' sample.vcf | tail -n 4
chr1 14653 . C T 100 QC_OK .
chr7 55191822 . T G 210 QC_OK .
chr13 32316000 . G A 250 QC_OK .
chr17 7675088 . C T 18 LowQual .
Feature GNU sed macOS sed
In place, no backup sed -i 's/a/b/' f sed -i '' 's/a/b/' f
In place with backup sed -i.bak sed -i.bak
\t and \r escapes yes no
\U, \L case conversion yes no
One-line 1i text yes needs 1i\ and a newline
Step address 2~4p yes no
Extended regex -E or -r -E

gsed from Homebrew gives the GNU behavior on a Mac.

  • awk for column logic, sums, and FASTA records that span lines.
  • grep, find & pipes for searching and chaining commands.
  • Text Processing teaches sed alongside grep, cut, and awk.
  • VCF: Variants explains the header, contigs, and bcftools.
  • SLURM uses sed -n "${SLURM_ARRAY_TASK_ID}p" to pick a sample per array task.

The GNU sed manual explains substitution flags, back-references, and the special meaning of an ampersand in replacement text. These rules explain why a path delimiter alone does not quote arbitrary replacement values. Its address and range sections show which lines an edit reaches, while the GNU extension sections identify behavior that requires a separate check on another implementation.