sed (Stream Editor) is a powerful command-line utility in Linux for manipulating text. It processes input (files or streams) line by line, applying commands to search, replace, delete, insert, or transform text. It’s widely used in scripting, automation, and text processing tasks due to its efficiency and flexibility.
- Purpose: Edit text non-interactively by applying predefined commands.
- Key Feature: Processes text as a stream, reading one line at a time, modifying it, and outputting the result.
- Use Cases: Bulk text replacements, log filtering, configuration file edits, and more.
The general form of a sed command is:
sed [OPTIONS] 'COMMAND' [INPUT_FILE]OPTIONS: Modifysed’s behavior (e.g.,-ifor in-place edits).COMMAND: The action to perform (e.g.,s/old/new/for substitution).INPUT_FILE: The file to process (optional;sedcan read from a pipe if omitted).
-i: Edit the file in place (overwrites the original).-n: Suppress automatic printing of all lines (useful withpcommand).-e: Specify multiple commands in one run.-f: Read commands from a script file.
sed uses a simple scripting language. Here are the most common commands:
s/SEARCH_PATTERN/REPLACEMENT/FLAGS- Replaces text matching
SEARCH_PATTERNwithREPLACEMENT. - Flags:
g: Replace all occurrences on a line.i: Case-insensitive matching.- Number (e.g.,
2): Replace the nth occurrence only.
/pattern/d- Deletes lines matching the pattern.
/pattern/p- Prints lines matching the pattern (combine with
-nto suppress other output).
/pattern/i\TEXT- Inserts
TEXTbefore matching lines.
/pattern/a\TEXT- Appends
TEXTafter matching lines.
echo "Hello World" | sed 's/World/Linux/'- Output:
Hello Linux - Explanation: Replaces the first "World" with "Linux" on the line.
echo "cat cat dog" | sed 's/cat/bird/g'- Output:
bird bird dog - Explanation: The
gflag replaces all "cat" instances.
sed -i 's/error/warning/g' log.txt- Explanation: Replaces all "error" with "warning" in
log.txtand saves the changes.
sed '/error/d' log.txt- Output: Prints
log.txtwithout lines containing "error." - Explanation: The
dcommand removes matched lines.
sed can target specific lines or ranges:
sed '3s/cat/dog/' file.txt- Replaces "cat" with "dog" only on line 3.
sed '2,5s/cat/dog/g' file.txt- Replaces all "cat" with "dog" on lines 2 through 5.
sed '/start/,/end/s/cat/dog/g' file.txt- Replaces "cat" with "dog" between lines matching "start" and "end" (inclusive).
sed '$d' file.txt- Deletes the last line (
$represents the end).
sed supports regex for advanced pattern matching:
echo "Order 123 completed" | sed 's/[0-9]\+/ORDER_ID/g'- Output:
Order ORDER_ID completed - Explanation:
[0-9]\+matches one or more digits.
echo "cat caterpillar catnip" | sed 's/\bcat\b/fish/g'- Output:
fish caterpillar catnip - Explanation:
\bensures "cat" is a standalone word, not part of "caterpillar."
echo "start middle end" | sed 's/^start/begin/'- Output:
begin middle end - Explanation:
^anchors to the start of the line.
echo "John Doe" | sed 's/\(.*\) \(.*\)/\2, \1/'- Output:
Doe, John - Explanation:
\(\.*\)captures text;\1and\2reuse the captured groups.
echo "ID: 123" | sed 's/ID: \([0-9]\+\)/UserID: \1/'- Output:
UserID: 123 - Explanation: Captures digits after "ID:" and reuses them.
echo "hello world" | sed 's/\(.*\)/\U\1/'- Output:
HELLO WORLD - Explanation:
\Uconverts the captured text to uppercase.
sed -i.bak 's/error/warning/g' log.txt- Creates
log.txt.bakas a backup before modifyinglog.txt.
sed -i 's/old/new/g' *.txt- Applies the replacement to all
.txtfiles in the directory.
sed '/error/i\WARNING: Problem detected' log.txt- Adds "WARNING: Problem detected" before every line with "error."
sed '/completed/a\Timestamp: $(date)' status.txt- Adds a timestamp after lines with "completed."
sed '1i\Header Line' file.txt # Insert at start
sed '$a\Footer Line' file.txt # Append at endIf your pattern includes slashes (/), use a different delimiter (e.g., |):
sed 's|/var/www|/opt/app|g' config.txt- Explanation: Avoids escaping slashes, making the command readable.
Run several operations in one sed invocation:
sed -e 's/cat/dog/g' -e 's/mouse/rat/g' file.txt- Replaces "cat" with "dog" and "mouse" with "rat."
sed 's/cat/dog/g;s/mouse/rat/g' file.txt- Same as above, but more concise.
Create commands.sed:
s/cat/dog/g
s/mouse/rat/g
Run:
sed -f commands.sed file.txtecho "one two three" | sed 's/ .*//'- Output:
one - Explanation: Removes everything after the first space.
echo "Price: $99.99" | sed 's/[^0-9.]//g'- Output:
99.99 - Explanation: Keeps digits and dots, removes everything else.
echo "<p>Hello <b>World</b></p>" | sed 's/<[^>]*>//g'- Output:
Hello World - Explanation: Strips all HTML tags.
echo "too many spaces" | sed 's/ \+/ /g'- Output:
too many spaces - Explanation: Replaces multiple spaces with one.
sed '/debug/s/^/#/' config.txt- Adds
#to the start of lines with "debug."
- With
grep:
cat log.txt | sed 's/error/ERROR/g' | grep 'ERROR'-
Filters lines after transforming "error" to "ERROR."
-
With
find:
find . -name "*.txt" -exec sed -i 's/old/new/g' {} \;- Edits all
.txtfiles recursively.
| Tool | Strengths | Weaknesses |
|---|---|---|
sed |
Substitution, line edits | No math or field parsing |
awk |
Field extraction, calculations | Less focus on substitution |
grep |
Pattern matching | No editing capability |
- Test First: Run without
-ito preview changes. - Escape Special Characters: Use
\before.,*, etc., in patterns. - Debugging: Use
sed -n 'p'to see what’s being processed. - Backup: Always use
-i.bakfor critical files.
sedis a lightweight, line-based text processor.- excels at search/replace, deletions, insertions, and filtering.
- Supports regex for complex patterns.
- Highly scriptable and integratable with other Linux tools.
Create a file test.txt:
cat dog
bird cat
mouse
Run:
sed -e 's/cat/fish/g' -e '/mouse/d' test.txt- Output:
fish dog
bird fish