Skip to content

sed notes

September 29, 2023
January 13, 2015

sed (stream editor) is a Unix utility that parses and transforms text, using a simple, compact programming language.

sed 'commands' file
sed -f <PROGRAM.sed> file

Reference

Get sed savvy - part 1
Get sed savvy - part 2
Get sed savvy - part 3

Famous Sed One-Liners Explained, Part I: File Spacing, Numbering and Text Conversion and Substitution - good coders code, great reuse
Famous Sed One-Liners Explained, Part II: Selective Printing of Certain Lines - good coders code, great reuse
Famous Sed One-Liners Explained, Part III: Selective Deletion of Certain Lines and Special Applications - good coders code, great reuse
Cover - GNU SED
sed one-liners
Sed one-liners

Sed - UNIX Stream Editor - Cheat Sheet - good coders code, great reuse

Sed by Example, Part 1
Sed by Example, Part 2
Sed by Example, Part 3
Sed - An Introduction and Tutorial
Using Sed | DigitalOcean
sed 简明教程 | 酷 壳 - CoolShell.cn
Your Own Linux..!: sed
Text Manipulation with sed | Linux Journal

sed & awk, 2nd Edition

Examples

# trim leading and trailing whitespace
echo ${string} | sed 's/^[[:space:]]*\(.*\)[[:space:]]*$/\1/'

# search and replace in file (inplace)
sed -i 's/STRING_TO_REPLACE/STRING_TO_REPLACE_IT/g' file
# replace "apple" with "(apple)", not '&' is reference
sed s/apple/(&)/ file
# or use regex group
sed s/\(apple\)/(\1)/ file
# get n-th line from file
sed -n '<n> p' filename
echo filename | sed "<n>q;d"
# count length of line 10
sed -n '10 p' filename | wc -c
# insert at N-th line of file
sed -i 'N i <LINE-TO-BE-ADDED>' FILE.txt