sed
sed (Stream EDitor) is a command that processes text line by line. It performs editing operations such as substitution, deletion, insertion, and extraction without opening a file. It is commonly used in scripts and automated workflows.
Syntax
sed [options] 'command' [file...]
sed [options] -e 'command1' -e 'command2' [file...]
Commands and Options
| Command / Option | Description |
|---|---|
| s/before/after/ | Replaces the first match on each line. |
| s/before/after/g | Replaces all matches on each line (global). |
| s/before/after/i | Replaces matches case-insensitively. |
| -i file | Edits the file in place (directly). |
| -i.bak file | Saves a backup to .bak before editing in place. |
| -n | Suppresses default output (used together with the p command). |
| /pattern/d | Deletes lines matching the pattern. |
| /pattern/p | Prints lines matching the pattern (used together with -n). |
| Nd | Deletes line N. |
| N,Md | Deletes lines N through M. |
| /pattern/a text | Appends text after each matching line. |
| /pattern/i text | Inserts text before each matching line. |
Sample Code
The following files are used as examples.
data.txt
Hello World foo foo
This is a foo test
Another line here
config.txt
# Database settings
host=localhost
# Port number
port=3306
# Database settings host=localhost # Port number port=3306
s/before/after/ replaces the first match on each line. Adding g replaces all matches.
sed 's/foo/bar/' data.txt Hello World bar foo This is a bar test Another line here
sed 's/foo/bar/g' data.txt Hello World bar bar This is a bar test Another line here
/pattern/d deletes lines matching the pattern. The example below removes comment lines (lines starting with #).
sed '/^#/d' config.txt host=localhost port=3306
/^$/d removes blank lines.
printf "line1\n\nline2\n\nline3\n" | sed '/^$/d' line1 line2 line3
Combining -n and the p command extracts only specific lines.
sed -n '2,4p' config.txt host=localhost # Port number port=3306
-e runs multiple substitutions at once.
sed -e 's/foo/bar/g' -e 's/World/Earth/' data.txt Hello Earth bar bar This is a bar test Another line here
-i edits the file directly (in-place substitution). -i.bak creates a backup before editing.
sed -i 's/old/new/g' file.txt
sed -i.bak 's/old/new/g' file.txt
Removes leading and trailing whitespace (trim).
echo " hello world " | sed 's/^[[:space:]]*//; s/[[:space:]]*$//' hello world
Deletes the first line (useful for skipping CSV headers, for example).
echo -e "name,age\nalice,30\nbob,25" | sed '1d' alice,30 bob,25
Notes
When using sed -i for in-place editing, it is strongly recommended to create a backup first or work within a git-managed repository. On macOS, BSD sed is used instead of GNU sed, so some option syntax differs (for example, macOS requires an empty string: sed -i "").
For more complex text processing, use awk. For simple searches, see also grep.
If you find any errors or copyright issues, please contact us.