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.
Quick reference
Section titled “Quick reference”| 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 |
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.
An unsorted BED file and a long-format count table:
tr '|' '\t' > regions.bed <<'EOF'chr2|100|200|peak1chr1|50|150|peak2chr1|300|400|peak3chr3|500|700|peak4EOFtr '|' '\t' > counts.tsv <<'EOF'gene|sample|countTP53|ctrl_1|120TP53|trt_1|98BRCA1|ctrl_1|45BRCA1|trt_1|60EOFA VCF whose header declares its contigs with the chr prefix:
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|INFOchr1|14653|.|C|T|100|PASS|.chr7|55191822|.|T|G|210|PASS|.chr13|32316000|.|G|A|250|PASS|.chr17|7675088|.|C|T|18|LowQual|.EOFA FASTA file with descriptions in the headers and a soft-masked, lowercase stretch in seq2:
cat > sample.fa <<'EOF'>seq1 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq2 BRCA1 fragmentGATTTATCTGctcttcgcgTTGAAGAA>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCEOFA 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:
cat > samplesheet.csv <<'EOF'sample,fastq_1,fastq_2ctrl_1,/data/run01/ctrl_1_R1.fastq.gz,/data/run01/ctrl_1_R2.fastq.gztrt_1,/data/run01/trt_1_R1.fastq.gz,/data/run01/trt_1_R2.fastq.gzEOFprintf '%s\n' ctrl_1 ctrl_2 trt_1 trt_2 > samples.txtprintf 'TP53 120\nMYC 30\n' > messy.txtprintf '%s\r\n' 'sample,condition' 'ctrl_1,control' 'trt_1,treated' \ > from_excel.csvSubstitution
Section titled “Substitution”s/pattern/replacement/ replaces the first match on each line. A g flag replaces every match
and a number replaces only that occurrence:
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,chr31,2,3chr1,2,chr3Capture groups
Section titled “Capture groups”-E turns on extended regex, so ( ) and + need no backslash. \1 and \2 refer back to
the groups:
sed -E 's/^>(seq[0-9]+) ([A-Z0-9]+) .*/>\2|\1/' sample.fa>TP53|seq1ATGGAGGAGCCGCAGTCAGATCCTAGC>BRCA1|seq2GATTTATCTGctcttcgcgTTGAAGAA>EGFR|seq3ATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCReuse the whole match
Section titled “Reuse the whole match”& in the replacement stands for the text the pattern matched:
sed 's/^>seq[0-9]*/&_GRCh38/' sample.fa>seq1_GRCh38 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq2_GRCh38 BRCA1 fragmentGATTTATCTGctcttcgcgTTGAAGAA>seq3_GRCh38 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCUse another delimiter for paths
Section titled “Use another delimiter for paths”Any character after s becomes the delimiter, so a path needs no escaped slashes:
sed 's|/data/run01/|/scratch/project/fastq/|g' samplesheet.csvsample,fastq_1,fastq_2ctrl_1,/scratch/project/fastq/ctrl_1_R1.fastq.gz,/scratch/project/fastq/ctrl_1_R2.fastq.gztrt_1,/scratch/project/fastq/trt_1_R1.fastq.gz,/scratch/project/fastq/trt_1_R2.fastq.gzUse a shell variable
Section titled “Use a shell variable”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:
old_run=run01new_run=run02sed "s/${old_run}/${new_run}/g" samplesheet.csvsample,fastq_1,fastq_2ctrl_1,/data/run02/ctrl_1_R1.fastq.gz,/data/run02/ctrl_1_R2.fastq.gztrt_1,/data/run02/trt_1_R1.fastq.gz,/data/run02/trt_1_R2.fastq.gzSeveral edits in one pass
Section titled “Several edits in one pass”sed -e 's/^>seq/>contig_/' -e 's/ fragment$//' sample.fa>contig_1 TP53ATGGAGGAGCCGCAGTCAGATCCTAGC>contig_2 BRCA1GATTTATCTGctcttcgcgTTGAAGAA>contig_3 EGFRATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCEdit a file in place
Section titled “Edit a file in place”-i.bak edits the file and keeps the original as regions_edit.bed.bak. Practice on a copy
first:
cp regions.bed regions_edit.bedsed -i.bak 's/^chr//' regions_edit.bedhead -n 2 regions_edit.bed regions_edit.bed.bak==> regions_edit.bed <==2 100 200 peak11 50 150 peak2
==> regions_edit.bed.bak <==chr2 100 200 peak1chr1 50 150 peak2GNU 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.
VCF recipes
Section titled “VCF recipes”Strip the chr prefix from records
Section titled “Strip the chr prefix from records”/^#/! applies the substitution to every line that does not start with #:
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 INFO1 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.
Rename in the header and the records
Section titled “Rename in the header and the records”sed -E -e '/^#/!s/^chr//' -e 's/^(##contig=<ID=)chr/\1/' sample.vcf \ > nochr.vcfcat 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 INFO1 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.
Add the chr prefix back
Section titled “Add the chr prefix back”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 INFOchr1 14653 . C T 100 PASS .chr7 55191822 . T G 210 PASS .chr13 32316000 . G A 250 PASS .chr17 7675088 . C T 18 LowQual .FASTA recipes
Section titled “FASTA recipes”Keep only the ID in each header
Section titled “Keep only the ID in each header”Many tools stop reading a header at the first space. The /^>/ address keeps sequence lines out
of the edit:
sed '/^>/s/ .*//' sample.fa>seq1ATGGAGGAGCCGCAGTCAGATCCTAGC>seq2GATTTATCTGctcttcgcgTTGAAGAA>seq3ATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCPrint the headers
Section titled “Print the headers”-n turns off the automatic print and p prints the lines that match:
sed -n '/^>/p' sample.fa>seq1 TP53 fragment>seq2 BRCA1 fragment>seq3 EGFR fragmentUppercase soft-masked bases
Section titled “Uppercase soft-masked bases”\U is a GNU extension. On macOS use awk '!/^>/ {$0 = toupper($0)} 1' instead.
sed '/^>/!s/.*/\U&/' sample.fa>seq1 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq2 BRCA1 fragmentGATTTATCTGCTCTTCGCGTTGAAGAA>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCDelete one record
Section titled “Delete one record”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.
sed '/^>seq2 /,/^>/{/^>seq2 /d;/^>/!d;}' sample.fa>seq1 TP53 fragmentATGGAGGAGCCGCAGTCAGATCCTAGC>seq3 EGFR fragmentATGCGACCCTCCGGGACGGCCGGGGCAGCGCTCCTGGCGCTGCTGGCTGCGCTCseqkit grep -v -p seq2 matches the ID exactly and is the tool for large files.
Reverse complement one sequence
Section titled “Reverse complement one sequence”y maps characters one to one, like tr. It gives the complement, and rev reverses it:
echo 'ATGAAACCC' | sed 'y/ACGT/TGCA/'echo 'ATGAAACCC' | sed 'y/ACGT/TGCA/' | revTACTTTGGGGGGTTTCATTable recipes
Section titled “Table recipes”Delete the header line
Section titled “Delete the header line”sed '1d' counts.tsvTP53 ctrl_1 120TP53 trt_1 98BRCA1 ctrl_1 45BRCA1 trt_1 60Insert a header line
Section titled “Insert a header line”The one-line form of i and the \t escape are GNU extensions:
sed '1i chrom\tstart\tend\tname' regions.bedchrom start end namechr2 100 200 peak1chr1 50 150 peak2chr1 300 400 peak3chr3 500 700 peak4Turn runs of spaces into tabs
Section titled “Turn runs of spaces into tabs”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'.
sed -E 's/ +/\t/g' messy.txt | cat -ATP53^I120$MYC^I30$Remove Windows line endings
Section titled “Remove Windows line endings”The ^M before each $ is the carriage return that breaks column matching and sample names:
cat -A from_excel.csvsample,condition^M$ctrl_1,control^M$trt_1,treated^M$sed 's/\r$//' from_excel.csv | cat -Asample,condition$ctrl_1,control$trt_1,treated$\r in a pattern is GNU only. tr -d '\r' works everywhere.
Remove blank lines
Section titled “Remove blank lines”printf 'TP53\n\nMYC\n \nEGFR\n' | sed '/^[[:space:]]*$/d'TP53MYCEGFRRemove comment lines
Section titled “Remove comment lines”sed '/^#/d' sample.vcfchr1 14653 . C T 100 PASS .chr7 55191822 . T G 210 PASS .chr13 32316000 . G A 250 PASS .chr17 7675088 . C T 18 LowQual .Addresses
Section titled “Addresses”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.
Print a range of lines
Section titled “Print a range of lines”sed -n '2,4p' counts.tsvTP53 ctrl_1 120TP53 trt_1 98BRCA1 ctrl_1 45Print line N from a variable
Section titled “Print line N from a variable”This is how a SLURM array task picks its sample, with the task ID in place of task_id:
task_id=3sed -n "${task_id}p" samples.txttrt_1Stop after N lines
Section titled “Stop after N lines”3q prints three lines and exits, so sed does not read the rest of a large file:
sed 3q counts.tsvgene sample countTP53 ctrl_1 120TP53 trt_1 98Apply an edit to all but the header
Section titled “Apply an edit to all but the header”sed '/^#/!s/PASS/QC_OK/' sample.vcf | tail -n 4chr1 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 .GNU sed and macOS sed
Section titled “GNU sed and macOS sed”| 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.
See also
Section titled “See also”- 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.
Further reading
Section titled “Further reading”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.