sed 's/dog/cat/' file.txt
Replaces the first occurrence of "dog" with "cat" in each line.
sed 's/dog/cat/g' file.txt
g replaces all instances of "dog" in each line.
sed '3d' file.txt
Deletes the 3rd line of the file.
sed '/error/d' log.txt
Removes all lines containing the word "error".
sed '/START/a New text line' file.txt
Adds "New text line" after lines matching "START".
sed '/END/i Inserted line' file.txt
Inserts "Inserted line" before lines with "END".
sed -n '/warning/p' log.txt
-n suppresses output except for matching lines.
sed 's/[0-9][0-9]/XX/g' file.txt
Replaces all two-digit numbers with "XX".
sed 's/old/new/g' file.txt
Same as Example 2, but emphasized for clarity.
sed '/^$/d' file.txt
Removes empty lines (^ matches start, $ end of line).
sed 's/\t/ /g' file.txt
Replaces each tab with four spaces.
sed '1!G;h;$!d' file.txt
A classic trick to reverse the order of lines.
sed -n '$=' file.txt
Returns the total number of lines (alternative to `wc -l`).
sed '=' file.txt | sed 'N;s/\n/ /'
Numbers each line (requires two passes).
sed 's/\(.*\) \(.*\)/\2 \1/' file.txt
Swaps the first and second words (uses backreferences).
sed 's/[^ ]*//3' file.txt
Extracts the third space-separated column.
sed -e '1h;1d' -e '$!H;$!d' -e 'g' file.txt
Swaps first and last lines (advanced example).
sed -i.bak 's/error/warning/g' file.txt
Modifies the file and saves a backup as `file.txt.bak`.
sed 's/old/new/; s/error/warning/' file.txt
Performs two substitutions sequentially.
sed -E 's/(old|existing)/new/g' file.txt
Uses `-E` for more readable regex (e.g., `|` for OR).
sed 's/\(.*warning\).*/\1/' file.txt
Truncates lines at "warning" (keeps everything before).
sed 's/dog/cat/3' file.txt
Replaces only the third "dog" in each line.
sed "s/old/$NEW_VAR/g" file.txt
Substitutes using shell variables (e.g., `NEW_VAR="new"`).
sed 's/<\/div>/\n<\/div>/g' file.html
Adds a newline before closing `</div>` tags.
sed '/start/{:a;N;/end/b;p;d;ba}' file.txt
Prints only text between "start" and "end" markers.
| Command | Description |
|---|---|
s/pattern/replacement/ |
Substitute occurrences of pattern. |
d |
Delete lines matching criteria. |
i and a |
Insert or append text before/after lines. |
-i |
Edit files in-place (add .bak for backups). |
-n |
Suppress automatic printing (use p explicitly). |
g at the end of s/// to replace all occurrences in a line./pattern/ or line numbers restrict commands to specific lines.\., \*) in regex patterns.-i is destructive—always use -i.bak to keep backups.