Privacy Policy
© 2025 linux101.dev

sed Command Cheatsheet

The sed (stream editor) command is a powerful utility for parsing and transforming text. It is most commonly used for finding and replacing text, either in a file or from a piped stream.

Common Syntax

The most basic and common usage of sed is for substitution.

sed 's/search_pattern/replacement_string/' [FILE]

The `s` command stands for `substitute`. The forward slashes (`/`) act as delimiters.

Substitution Flags

You can add flags at the end of the substitution command to modify its behavior.

FlagDescriptionExample
gGlobal replacement. Replaces all occurrences of the pattern on a line, not just the first one.sed 's/word/WORD/g' file.txt
iCase-insensitive replacement.sed 's/word/WORD/gi' file.txt
IAn alternative case-insensitive flag.sed 's/word/WORD/gI' file.txt
pPrint the modified line. Use with the -n option to only print matching lines.sed -n 's/word/WORD/p' file.txt

Important Options

OptionDescriptionExample
-iEdit files in-place. This option saves the changes directly to the file. Use with caution.sed -i 's/old/new/' file.txt
-i.bakEdit files in-place but create a backup of the original file.sed -i.bak 's/old/new/' file.txt
-nSuppresses automatic printing of pattern space. This is used in conjunction with the `p` flag to only print lines that have been modified.sed -n '/pattern/p' file.txt

Using `sed` with Pipelines

`sed` is often used at the end of a command chain to modify the output of another command.

# Use grep to find lines and sed to replace text on those lines
grep "error" /var/log/syslog | sed 's/error/critical error/'