🤖 BCH709 AI Assistant: Ask questions about this class using NotebookLM

BCH709 Introduction to Bioinformatics: sed - Stream Editor

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.txt
Hello 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.txt
HellO 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.txt
HellO WOrld
hellO wOrld
The quick brOwn fOx
Line with spaces
AnOther line
# Case-insensitive replace
sed 's/hello/Hi/i' sample.txt
Hi World
Hi world
The quick brown fox
Line with spaces
Another line

Step 2: Line Operations

# Print only line 3
sed -n '3p' sample.txt
The quick brown fox
# Print lines 2-4
sed -n '2,4p' sample.txt
hello world
The quick brown fox
Line with spaces
# Delete lines containing 'world'
sed '/world/d' sample.txt
The 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.txt
Hello 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