What is sed?
sed (Stream EDitor) is a non-interactive text editor that processes input one line at a time.
It is commonly used for:
-
Text replacement
-
Editing configuration files
-
Log processing
-
Shell scripting
-
CI/CD automation
Unlike Vim, sed edits a text stream automatically without opening an editor.
Basic Syntax
Read from a file:
sed 'command' file.txtRead from standard input:
command | sed 'command'Example:
echo "hello world" | sed 's/world/Linux/'Output:
hello LinuxThe Substitute Command
Syntax:
s/old/new/Meaning:
-
s= substitute -
old= search pattern -
new= replacement
Example:
echo "cat dog" | sed 's/cat/lion/'Output:
lion dogFirst Match vs All Matches
Default: replace only the first match on each line.
echo "cat cat cat" | sed 's/cat/dog/'Output:
dog cat catReplace every match:
echo "cat cat cat" | sed 's/cat/dog/g'Output:
dog dog dogg = global (all matches on the current line).
Using Another Delimiter
Useful for file paths.
Instead of:
sed 's/\/usr\/bin/\/opt\/bin/'Use:
sed 's|/usr/bin|/opt/bin|'Any character can be the delimiter as long as it is used consistently.
Edit a File In Place
Modify the original file:
sed -i 's/foo/bar/g' file.txtCreate a backup first:
sed -i.bak 's/foo/bar/g' file.txtResult:
file.txt
file.txt.bakCommon Examples
Replace tabs with spaces:
sed 's/\t/ /g'Remove trailing whitespace:
sed 's/[[:space:]]*$//'Replace a version number:
sed 's/v1.2/v2.0/'Template substitution:
VERSION="2.0"
sed "s/@VERSION@/$VERSION/g" config.template > config.confKey Takeaways
-
sedis a stream editor. -
The most common command is
s/old/new/. -
By default, only the first match on each line is replaced.
-
Add the
gflag to replace all matches. -
-iedits files directly. -
Using delimiters such as
|makes path substitutions easier to read.