sed Command Examples
1. Basic Deletion Examples
1.1 Delete specific lines
# Delete line 3
sed '3d' file.txt
# Delete lines 5-10
sed '5,10d' file.txt
# Delete last line
sed '$d' file.txt
1.2 Delete pattern-matched lines
# Delete lines containing "error"
sed '/error/d' file.txt
# Delete blank lines
sed '/^$/d' file.txt
2. Basic Printing Examples
2.1 Print specific lines
# Print only line 7
sed -n '7p' file.txt
# Print lines 20-30
sed -n '20,30p' file.txt
2.2 Print pattern-matched lines
# Print lines containing "warning"
sed -n '/warning/p' file.txt
# Print lines starting with "#" (comments)
sed -n '/^#/p' file.txt
3. Basic Substitution Examples
3.1 Simple text replacement
# Replace first "apple" with "orange" on each line
sed 's/apple/orange/' fruits.txt
# Replace ALL "cat" with "dog"
sed 's/cat/dog/g' pets.txt
3.2 Character-level replacements
# Replace tabs with spaces
sed 's/\t/ /g' file.txt
# Convert DOS line endings (CRLF) to Unix (LF)
sed 's/\r$//' dosfile.txt
4. Basic Insertion/Appending Examples
4.1 Add lines at specific positions
# Insert line before line 4
sed '4i\This is new text' file.txt
# Append line after line 8
sed '8a\This comes after' file.txt
# Add header to file
sed '1i\Title: My Document' doc.txt
5. Basic In-Place Editing
5.1 Modify files directly
# Edit file with backup
sed -i.bak 's/old/new/g' file.txt
# Edit file without backup (GNU sed)
sed -i 's/old/new/g' file.txt