sed Basics
Basic Substitution
The s/old/new/ command substitutes the first match of old with new on each line. Without a trailing g flag, only the first occurrence per line is replaced.
Example: Basic Substitution
#!/bin/bash
echo "cat sat on the cat mat" | sed 's/cat/dog/'
Login to try C/C++/Java/PHP code in the editor
Global Substitution
Adding a g flag after the third slash makes the substitution apply to every match on the line, not just the first one found.
Example: Global Substitution
#!/bin/bash
echo "cat sat on the cat mat" | sed 's/cat/dog/g'
Login to try C/C++/Java/PHP code in the editor
Editing a File in Place
sed -i 's/old/new/' file rewrites the file itself instead of printing the change to stdout. This is destructive, so it is worth testing the plain (non -i) version on a sample first.
Warning: sed -i overwrites the file with no confirmation; keep a backup or use version control before running it on important files.
Example: Editing a File in Place
#!/bin/bash
echo "version=1.0" > config.txt
sed -i 's/1.0/2.0/' config.txt
cat config.txt
rm -f config.txt
Login to try C/C++/Java/PHP code in the editor
Deleting Lines
sed Nd deletes line number N. sed '/pattern/d' deletes every line matching pattern anywhere in the line, which is a quick way to strip comments or blank lines.
Example: Deleting Lines
#!/bin/bash
printf "keep\n# comment\nkeep too\n# another comment\n" > notes.txt
sed '/^#/d' notes.txt
rm -f notes.txt
Login to try C/C++/Java/PHP code in the editor
- Forgetting
sedprints to stdout by default and does not modify the file unless-iis used. - Using
sed -ion macOS/BSD sed without an argument and hitting an error, since GNU sed and BSD sed have different-isyntax; on GNU/Linux (like this course's sandbox)-itakes no separate backup suffix unless one is given. - Not escaping special regex characters like
.or/in the pattern, causing sed to match more (or less) than intended.
sed 's/old/new/' filereplaces the first occurrence ofoldwithnewon each line.- Adding a
gflag (s/old/new/g) replaces every occurrence on each line, not just the first. sed -iedits a file in place instead of printing the result to stdout.sed 2d filedeletes line 2;sed '/pattern/d' filedeletes every line matching a pattern.
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: