sed - Stream Editor
sed performs text transformations on files. Great for find-and-replace.
Setup: Create Sample File
cat > sample.txt << 'EOF' Hello World hello world The quick brown fox Line with spaces Another line EOF cat sample.txtHello World hello world The quick brown fox Line with spaces Another line
Step 1: Basic Substitution
# Replace first 'o' with 'O' on each line sed 's/o/O/' sample.txtHellO World hellO world The quick brOwn fox Line with spaces AnOther line# Replace ALL 'o' with 'O' (global flag) sed 's/o/O/g' sample.txtHellO WOrld hellO wOrld The quick brOwn fOx Line with spaces AnOther line# Case-insensitive replace sed 's/hello/Hi/i' sample.txtHi World Hi world The quick brown fox Line with spaces Another line
Step 2: Line Operations
# Print only line 3 sed -n '3p' sample.txtThe quick brown fox# Print lines 2-4 sed -n '2,4p' sample.txthello world The quick brown fox Line with spaces# Delete lines containing 'world' sed '/world/d' sample.txtThe quick brown fox Line with spaces Another line
Step 3: Edit File In-Place
# Create a backup and edit cp sample.txt sample_backup.txt sed -i 's/World/Universe/g' sample.txt cat sample.txtHello Universe hello world The quick brown fox Line with spaces Another line
sed Quick Reference
| Command | Description |
|---|---|
s/old/new/ |
Replace first match |
s/old/new/g |
Replace all matches |
s/old/new/i |
Case-insensitive |
-n '5p' |
Print line 5 only |
/pattern/d |
Delete matching lines |
-i |
Edit file in-place |