Linux sed Command: Search and Replace Text Streams
sed is a stream editor that reads input line by line, applies editing rules, and outputs the results. It is suitable for repetitive text transformations, such as substitution, selecting specific lines, and deletion.
What is the sed command?
By default, it does not modify the original file and outputs the transformed result to standard output. The form of the substitution command is s/pattern_to_find/replacement_content/flags, and adding g replaces all matches in a line.
Basic syntax
sed [options] 'editing command' [file...]
Installed implementations and options may vary depending on the distribution. Check the description for your current system with man sed.
Examples
Substitute first match
Replaces only the first match in each line.
sed 's/old/new/' config.txt
Substitute all matches in a line
Use the g flag.
sed 's/old/new/g' config.txt
Print specific lines
Turn off automatic printing with -n and print ranges with p.
sed -n '5,10p' log.txt
Substitution Results and Whether the File Changes
The basic sed reads input and sends the transformed result to standard output without changing the original file. The substitution below changes only the first red in each line to green.
printf 'red car\nred red\n' | sed 's/red/green/'
Example output:
green car green red
To change all matches in a line, add g at the end of the substitution. Direct file modification -i has different backup suffix syntax depending on the implementation, so for important files, first make a backup and use sed '...' original > newfile to review the results before replacing.
To print only a range of lines, combine suppressed default output with an explicit print command, as in sed -n '5,10p' file. Sed regular expressions are not shell globs, and the shell can expand $ or backslashes inside double quotes before sed sees them. Check quoting and the substitution delimiter carefully.
Main Options and Format
| Options/Format | Description |
|---|---|
-n |
Turn off automatic printing by default. |
-e script |
Specify multiple editing commands. |
-E |
Use extended regular expressions. |
-i[suffix] |
Edit files in place and optionally make a backup in the GNU implementation. |
Precautions when using
`sed -i` actually modifies the file, so use a backup suffix for important files and review the results. The `-i` syntax differs between GNU and BSD. You also need to consider shell quoting and special characters in regular expressions.
Frequently Asked Questions
Does running just sed change the original file?
No. By default, it outputs the changed result. You need to use `-i` or save the result to a separate file to modify the file.
Official Documentation
You can check the exact behavior of options and differences between implementations in the official sed documentation.









