Sed Command in Linux: Complete Guide with Powerful Examples

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 -i flag.

  • 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

OptionDescription
-nSuppress automatic printing of pattern space.
-eAllows multiple expressions to be executed.
-iEdits files in place (modifies the file directly).
-rEnables extended regular expressions.
-fReads 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

sed -n -e '5,7p' -e '10,13p' itsmarttricks.txt
The -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 's/version/story/gi' myfile.txt

5. Replace Words Inside a Specific Range

sed '30,40 s/version/story/g' itsmarttricks.txt
Only replaces the word in lines 30 to 40.

6. Remove Comments or Empty Lines

To remove comments and blank lines from configuration files:

sed '/^#\|^$\| *#/d' httpd.conf
This is handy when reviewing clean configuration directives.

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 .conf files.

  • Log analysis: Extract or remove unwanted entries in log files.

  • Text formatting: Reformat CSV or text data for reports.

  • Automation: Combine sed in shell scripts for CI/CD pipelines.

  • Web updates: Bulk-replace URLs or metadata in HTML files.

Sed Command vs. Awk Command

FeatureSedAwk
Primary UseStream editingData analysis & reporting
OutputTransforms textPrints formatted results
SyntaxSimple substitutionScript-like syntax
PerformanceFaster for substitutionsBetter for data tables

 

For substitution-heavy tasks, the sed command is faster and easier.

Best Practices When Using Sed Command

  1. Always test commands before applying with -i.

  2. Use single quotes to avoid shell variable conflicts.

  3. Combine with grep or awk for advanced text workflows.

  4. Keep a backup (-i.bak) before bulk replacements.

  5. 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.txt

3. 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' filename

This 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:

Share this:
WhatsApp Channel Join Now
Telegram Channel Join Now
Instagram Channel Join Now

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.