The sed command, short for Stream Editor, is one of the most powerful text-processing tools in Linux. It allows users to search, replace, insert, and delete text in files or data streams — all without opening the file in an editor. Whether you’re an experienced Linux administrator or a beginner learning shell scripting, understanding the sed command can save you hours of manual work.
In Linux automation and system administration, sed is commonly used to automate repetitive text edits, remove comments, filter logs, and reformat data. It supports regular expressions (regex), enabling complex pattern matching.
What is the Sed Command in Linux?
The sed command is a non-interactive text editor that processes input line by line. It reads text from standard input (stdin) or a file, applies the specified operations, and outputs the result to standard output (stdout).
Basic syntax:
sed [options] 'command' filename
Key Features of the Sed Command
Performs text transformation without manual intervention.
Supports in-place editing using the
-iflag.Works with powerful regex patterns.
Useful for large-scale text or configuration file updates.
Integrates easily in shell scripts for automation.
Common Sed Command Options
| Option | Description |
|---|---|
-n | Suppress automatic printing of pattern space. |
-e | Allows multiple expressions to be executed. |
-i | Edits files in place (modifies the file directly). |
-r | Enables extended regular expressions. |
-f | Reads commands from a file. |
Useful Sed Command Examples in Linux
Below are practical sed command examples (based on the attached file and official Linux documentation) that every SysAdmin should know.
1. View a Range of Lines from a File
To print specific lines (for example, lines 5 to 10):
sed -n '5,10p' itsmarttricks.txt
This prints only the specified range, similar to combining head and tail.
2. Exclude a Range of Lines
To print everything except lines 20 to 35:
sed '20,35d' myfile.txt
This removes the given range and prints the rest.
3. Display Multiple Non-Consecutive Ranges
-e flag lets you combine multiple commands in one line.4. Replace a Word or String Globally
To replace “version” with “story” in a file:
sed 's/version/story/g' itsmarttricks.txt
For case-insensitive replacement, use:
sed '30,40 s/version/story/g' itsmarttricks.txt
6. Remove Comments or Empty Lines
To remove comments and blank lines from configuration files:
sed '/^#\|^$\| *#/d' httpd.conf
7. Case-Insensitive Word Replacement
To replace both Zip and zip with rar:
sed 's/[Zz]ip/rar/g' itsmarttricks.txt
8. Extract Specific Events from a Log File
To display log entries from July 1:
sed -n '/^Jul 1/p' /var/log/secure
This helps isolate specific date-based log patterns.
9. Insert Blank Lines in a File
To add a blank line after every existing line:
sed G itsmarttricks.txt
To add two blank lines:
sed 'G;G' itsmarttricks.txt
10. Remove Hidden DOS Characters (^M)
If you see strange ^M characters in files copied from Windows:
sed -i 's/\r//' myfile.txt
This removes carriage returns and converts files to Unix format.
11. Delete Specific Lines Containing a Pattern
Remove all lines containing “error”:
sed '/error/d' logfile.txt
12. Insert Text Before a Line Number
To insert “# Config updated” before line 3:
sed '3i # Config updated' file.conf
13. Append Text After a Line
sed '3a This is a new line' file.txt
Adds text after line 3.
14. Replace Only the First Occurrence on Each Line
sed 's/story/version/' myfile.txt
The g flag is omitted to replace only the first match per line.
15. Save Changes In-Place
To modify a file directly:
sed -i 's/http/https/g' index.html
The -i flag is powerful—use it carefully to avoid overwriting data.
You can create a backup before applying:
sed -i.bak 's/http/https/g' index.html
Real-World Use Cases of Sed Command
Configuration management: Clean up or edit multiple
.conffiles.Log analysis: Extract or remove unwanted entries in log files.
Text formatting: Reformat CSV or text data for reports.
Automation: Combine
sedin shell scripts for CI/CD pipelines.Web updates: Bulk-replace URLs or metadata in HTML files.
Sed Command vs. Awk Command
| Feature | Sed | Awk |
|---|---|---|
| Primary Use | Stream editing | Data analysis & reporting |
| Output | Transforms text | Prints formatted results |
| Syntax | Simple substitution | Script-like syntax |
| Performance | Faster for substitutions | Better for data tables |
For substitution-heavy tasks, the sed command is faster and easier.
Best Practices When Using Sed Command
Always test commands before applying with
-i.Use single quotes to avoid shell variable conflicts.
Combine with
greporawkfor advanced text workflows.Keep a backup (
-i.bak) before bulk replacements.Use regex cautiously; test small samples first.
Conclusion
The sed command remains one of the most essential Linux tools for text editing, automation, and data transformation. Whether you’re filtering logs, updating configuration files, or performing mass replacements, sed offers a fast, reliable, and scriptable way to handle large text data efficiently.
By mastering the examples and best practices shared above, you can harness the true power of the sed command in Linux — an invaluable skill for every system administrator and DevOps engineer.
FAQs About Sed Command
1. What is the sed command used for?
The sed command is used to automate text editing tasks such as search, replace, delete, and insert in Linux.
2. How can I edit files directly with sed?
Use the -i option for in-place editing:
sed -i 's/foo/bar/g' file.txt3. Can sed command handle regular expressions?
Yes. The sed command supports both basic and extended regular expressions for advanced pattern matching.
4. How do I remove empty lines with sed?
sed '/^$/d' filenameThis removes all blank lines from the file.
5. Is sed faster than awk?
For simple substitutions and deletions, the sed command is typically faster than awk due to its lightweight design.
Suggested Read:
- Use sed and awk to Modify Config Files in Linux — Complete Guide for Sysadmins
- How to Auto Execute Commands and Scripts at Reboot or Startup on Linux
- How to manipulate Process Priority in Linux using nice and renice Commands
- Linux Networking Commands for Sysadmins: A Complete Guide
- How to Install Webmin with SSL in Linux – A Web Interface to Configure Linux
- How to Check Exit Status in Linux Commands (Bash Examples)
