Introduction to Sed
Sed (Stream Editor) is a lightweight yet powerful Unix/Linux command-line tool for parsing and transforming text. It processes input line-by-line, making it ideal for automated editing tasks without manual file manipulation. Think of it as a “search-and-replace wizard” for your terminal!
🔧 Basic Syntax
sed [options] 'command' filename
options
: Flags like-i
(in-place edit),-n
(suppress output)command
: Operations like substitution (s
), deletion (d
), etc.
✨ Core Operations & Examples
1️⃣ Substitution (s
command)
Replace text patterns. Syntax: s/pattern/replacement/flags
Example 1: Replace first occurrence per line
echo "Hello World" | sed 's/World/Linux/'
# Output: Hello Linux
Example 2: Global replacement (all occurrences)
echo "apple apple" | sed 's/apple/orange/g'
# Output: orange orange
Example 3: Case-insensitive replacement
echo "Cat CAT cat" | sed 's/cat/dog/gi'
# Output: dog dog dog
2️⃣ Deletion (d
command)
Remove lines matching a pattern.
Example 1: Delete lines containing “error”
sed '/error/d' logfile.txt
Example 2: Delete lines 3-5
sed '3,5d' data.txt
3️⃣ Insertion/Appending (i
and a
commands)
Add text before (i
) or after (a
) a line.
Example: Add header before line 1
sed '1i\---HEADER---' notes.txt
Example: Append footer after last line
sed '$a\---END---' report.txt
4️⃣ Printing Specific Lines (p
command)
Use with -n
to suppress default output.
Example: Print lines 5-10
sed -n '5,10p' document.txt
🚀 Advanced Tips
- Multiple Commands: Separate with
;
sed 's/foo/bar/; s/baz/qux/' file.txt
- Edit Files In-Place: Use
-i
(backup with-i.bak
)sed -i.bak 's/old/new/g' file.txt # Creates backup file.txt.bak
- Regex Power: Use
.*
(any character),^
(start),$
(end)sed '/^#/d' script.sh # Delete all comment lines
⚠️ Important Notes
- Sed processes lines sequentially – commands apply to each line individually.
- Original files remain unchanged unless
-i
is used. - Delimiters (
/
) can be replaced (e.g.,s|old|new|
if text contains/
).
💡 Practice Exercise
Try replacing all “2023” dates with “2024” in dates.txt
and save changes:
sed -i 's/2023/2024/g' dates.txt
Conclusion
Sed is indispensable for quick text transformations. Start with simple substitutions (s/old/new/
), experiment with deletion/insertion, and leverage regex for complex tasks. Once mastered, you’ll handle log files, configs, and data like a pro! 🐧