sed — stream text substitution
💬 "sed command"
sed processes text as a stream to perform substitution and deletion. It is often used for batch changes to configuration files.
-i modifies files directly; to avoid mistakes, it is best to use a backup extension as well.
- Concept: Replaces or deletes matching parts of an input stream.
- s///: The basic form of the substitution command.
- -i: Modifies files directly.
- -n + p: Prints only specific lines.
Commonly used options
| Option | Description |
|---|---|
| -i.bak | Backs up the original to .bak before modification |
| s/old/new/g | Replaces all matches |
| -E | Uses extended regular expressions |
| -n '/pattern/p' | Prints only lines matching the pattern |
3 essential command combinations
sed -i.bak 's/10.0.0.5/10.0.0.9/g' /etc/app/config.yml— Batch-change IPs in a configuration (with backup)sed -n '/^server_name/p' /etc/nginx/nginx.conf— Extract only specific configuration linessed '/^#/d;/^$/d' /etc/app/config.yml | head— Remove comments and blank lines for viewing
💬 "Create an example that includes how to undo this operation"
Here are common situations on production servers, organized step by step.
Step 1 · Check the current value
Check the target string before changing it.
grep -n '10.0.0.5' /etc/app/config.yml
Step 2 · Replace (with backup)
Use -i.bak to keep the original while replacing.
sed -i.bak 's/10.0.0.5/10.0.0.9/g' /etc/app/config.yml
Step 3 · Verify
Check the result and confirm the service reflects it.
grep -n '10.0.0.9' /etc/app/config.yml && systemctl restart myapp
In practice, this is how it is used
1. Replace configuration IPs
Scenario — Change IPs in the configuration due to a database server migration.
sed -i.bak 's/10.0.0.5/10.0.0.9/g' /etc/app/config.yml
Result — All references are changed to the new IP, and the original remains in .bak.
Key point — Check the number of matches with grep before replacing to avoid omissions or over-replacement.
2. Compare settings by removing comments
Scenario — You want to see only the settings that actually apply.
sed '/^#/d;/^$/d' /etc/nginx/nginx.conf | head -30
Result — You see the actual settings with comments and blank lines removed.
Key point — Because the original is not modified, you can check safely.
Things to watch out for
- -i modifies files directly. Always include a backup extension.
- If the string to replace contains /, change the delimiter (e.g., s|a|b|g).
- Regular expression special characters need to be escaped.
Actual execution output
This is the result of batch-replacing configuration IPs with a backup and verifying them.
!sed command execution result: batch configuration replacement
Actual production server
Source (HTML): https://games.aidebatehub.com/programs/linux/automation/sed.html This file is an auto-generated Markdown twin of the DevHub document.
AI Knowledge Hub
Visitor Comments