Skip to main content
The s (substitute) command in sed is a powerful tool for search-and-replace operations on text streams. Whether you’re updating configuration files, automating code refactoring, or cleaning log files, mastering sed substitution will streamline your workflow.
By default, sed reads from stdin or an input file and writes to stdout. Use the -i option for in-place editing.

Table of Contents

  1. Basic Syntax
  2. Quick Reference Commands
  3. Practical Example: Updating a Salary
  4. Substitution Scope
  5. Targeting Specific Occurrences
  6. Line Addressing
  7. In-Place Editing (-i)
  8. Inserting Text with i
  9. Conclusion
  10. References

Basic Syntax

Use the following pattern to substitute old_string with new_string:
  • s     — substitute command
  • old_string — search pattern (regular expression supported)
  • new_string — replacement text
  • /     — delimiters (can be any character)
  • By default, only the first match per line is replaced.

Quick Reference Commands


Practical Example: Updating a Salary

Given an employees.txt file:
The image shows a text file named "employees.txt" containing a list of employees with details such as name, department, job title, email, and salary.
To update Enrique Rivera’s salary from 65000 to 85000, run:
This command replaces the first occurrence of 65000 on each line and prints the result to stdout.

Substitution Scope

Global Replacement

Append the g flag to replace all matches in each line:

First-Match Only

Without g, only the first match is replaced:

Targeting Specific Occurrences

You can replace only the nth occurrence on each line by specifying a number:
The above replaces only the second IT per line.

Line Addressing

Limit substitutions to certain lines or ranges:
  • Single line (line 7):
  • Line range (lines 1–3):
  • Another single line (line 5):

In-Place Editing (-i)

Modify the file directly using -i:
This updates all instances of company in employees.txt.
When using -i, changes are irreversible unless you create a backup:
This creates file.txt.bak before editing.

Inserting Text with i

The i command inserts lines before the current pattern space or at a specified line:
Output:
If you omit the text after i, sed throws an error:

Conclusion

In this guide, you learned how to:
  • Use s/old/new/ for basic substitution
  • Leverage g and numeric flags for global or specific replacements
  • Address lines and ranges for targeted edits
  • Apply in-place editing with -i (and backups)
  • Insert new lines using the i command
Together, these techniques form the foundation of efficient text processing with sed.

References

Watch Video

Practice Lab