|

Linux CLI 46 🐧 sed command

sed -n '=;p' example.txt
sed 's/This/That/g' example.txt
sed '/This/d' example.txt
sed -e 's/This/That/g' -e 's/And/---/' example.txt
echo "s/This/That/g" > scriptFile
sed -f scriptFile example.txt
sed -s 's/This/That/g' example.txt example1.txt

sed (stream editor) is the most versatile text-transformation tool on Linux. It reads input line by line, applies a script of editing commands, and writes the result to stdout. It can substitute, delete, insert, append, and print — all without opening an editor.

Key point: sed works on a stream — a file, a pipe, or a command’s output. By default it doesn’t modify the original file; it prints the transformed text to stdout. Use -i to edit in place.


a – sed command and options

sed is a text-processing tool. It can perform basic text transformations on an input stream — a file or command output.

Syntax:

sed [options] 'script' inputfile
  • script — the editing commands sed will execute
  • inputfile — the file(s) to process (or stdin if omitted)

Common options:

OptionPurpose
-iEdit files in place (saves changes to the original)
-e SCRIPTAdd a script to the list of editing commands (for multiple scripts)
-f FILERead editing commands from FILE
-nSuppress automatic printing of the pattern space
-E / -rUse extended regex
-sTreat files as separate streams (not one long stream)
-zUse NUL as the line separator

Examples:

# Basic substitution — prints result to stdout
$ cat example.txt
This is a test
And this is another line
This is the end

$ sed 's/This/That/' example.txt
That is a test
And this is another line
That is the end

# The original file is unchanged
$ cat example.txt
This is a test
And this is another line
This is the end

# Edit in place
$ sed -i 's/This/That/g' example.txt
$ cat example.txt
That is a test
And this is another line
That is the end

# Make a backup with -i
$ sed -i.bak 's/That/This/g' example.txt
$ ls example.txt*
example.txt  example.txt.bak

# Multiple scripts with -e
$ sed -e 's/This/That/g' -e 's/And/---/' example.txt

# Suppress auto-print with -n (only print what you ask for)
$ sed -n '2p' example.txt
And this is another line

# Read scripts from a file with -f
$ echo "s/This/That/g" > scriptFile
$ sed -f scriptFile example.txt

# Treat files separately with -s
$ sed -s 's/This/That/g' example.txt example1.txt

# Extended regex
$ sed -E 's/(foo|bar)/X/g' file.txt

⚠️ Warning: -i edits the file in place with no undo. Test your script without -i first, or always use -i.bak to keep a backup.


b – sed common scripts

A sed script is a sequence of commands. Most commands consist of an address (which lines to act on) and an operation (what to do).

ScriptMeaning
s/what/with/Substitute what with with
s/what/with/3Substitute only the 3rd occurrence on each line
s/what/with/3gSubstitute from the 3rd occurrence onward
s/what/with/gSubstitute all occurrences (global)
3 s/what/with/Substitute on line 3 only
n,mdDelete lines from n to m
n a\ textAppend text after line n
/pattern/pPrint lines matching pattern

Address forms:

AddressMatches
(none)Every line
NLine N
N,MLines N through M
$Last line
/regex/Lines matching regex
/regex1/,/regex2/Range between two patterns
N!NOT line N

Substitution flags:

FlagMeaning
gGlobal — all occurrences on the line
NReplace only the Nth occurrence
NgReplace from the Nth occurrence onward
pPrint the line if a substitution was made
iCase-insensitive match
w FILEWrite the line to FILE

Examples:

# Replace first occurrence on each line
$ echo "foo foo foo" | sed 's/foo/bar/'
bar foo foo

# Replace all occurrences
$ echo "foo foo foo" | sed 's/foo/bar/g'
bar bar bar

# Replace only the 2nd occurrence
$ echo "foo foo foo" | sed 's/foo/bar/2'
foo bar foo

# Replace from the 3rd occurrence onward
$ echo "foo foo foo foo" | sed 's/foo/bar/3g'
foo foo bar bar

# Replace on line 3 only
$ sed '3 s/This/That/' example.txt

# Delete a range of lines
$ sed '2,4d' file.txt
# Deletes lines 2 through 4

# Delete lines matching a pattern
$ sed '/This/d' example.txt

# Print only matching lines (with -n)
$ sed -n '/This/p' example.txt

# Append text after line 3
$ sed '3 a\ This is a new line' file.txt

# Insert text before line 1
$ sed '1 i\ Header line' file.txt

# Change an entire line
$ sed '2 c\ Replaced line' file.txt

More commands you’ll use often:

CommandPurpose
pPrint the current line
dDelete the current line
a\ textAppend text after the line
i\ textInsert text before the line
c\ textChange (replace) the line
y/abc/xyz/Transliterate characters (like tr)
qQuit after the current line
=Print the line number
nRead the next line

c – sed examples

Here are the practical examples you’ll reach for most often.

1. Print line numbers along with the content:

$ cat example.txt
This is a test
And this is another line
This is the end

$ sed -n '=;p' example.txt
1
This is a test
2
And this is another line
3
This is the end

The = prints the line number, ; separates commands, and p prints the line. The -n suppresses the default printing so you only see what the script produces.

2. Replace “This” with “That” everywhere:

$ sed 's/This/That/g' example.txt
That is a test
And this is another line
That is the end

3. Delete all lines containing “This”:

$ sed '/This/d' example.txt
And this is another line

4. Replace multiple patterns with -e:

$ sed -e 's/This/That/g' -e 's/And/---/' example.txt
That is a test
--- this is another line
That is the end

Each -e adds another script. They run in order on each line.

5. Create a script file and use it with -f:

$ echo "s/This/That/g" > scriptFile
$ cat scriptFile
s/This/That/g

$ sed -f scriptFile example.txt
That is a test
And this is another line
That is the end

6. Apply a substitution to multiple files with -s:

$ sed -s 's/This/That/g' example.txt example1.txt

Without -s, sed treats multiple files as one continuous stream — line numbers and the $ anchor span all files. With -s, each file is treated independently.

More practical examples:

# Delete empty lines
$ sed '/^$/d' file.txt

# Delete lines starting with #
$ sed '/^#/d' file.txt

# Remove trailing whitespace
$ sed 's/[[:space:]]*$//' file.txt

# Add a blank line after every line
$ sed G file.txt

# Double-space a file
$ sed G file.txt

# Remove duplicate blank lines
$ sed '/^$/{N;/^\n$/D}' file.txt

# Print the last line
$ sed -n '$p' file.txt

# Print lines 10–20
$ sed -n '10,20p' file.txt

# Insert a line after a pattern
$ sed '/pattern/a\ new line' file.txt

# Replace a whole line matching a pattern
$ sed '/pattern/c\ replacement line' file.txt

# Convert DOS line endings to Unix
$ sed 's/\r$//' windows.txt > unix.txt

# Extract a range between two patterns
$ sed -n '/START/,/END/p' file.txt

# Remove HTML tags (basic)
$ sed 's/<[^>]*>//g' page.html

# Number non-empty lines
$ sed '/./=' file.txt | sed '/./N; s/\n/ /'

# Comment out lines matching a pattern
$ sed '/pattern/ s/^/#/' file.txt

# Uncomment lines
$ sed '/^#/ s/^#//' file.txt

# Delete everything except lines matching a pattern
$ sed -n '/pattern/p' file.txt

# Replace with the content of a variable (shell)
$ sed "s/foo/$BAR/g" file.txt

# In-place edit with backup
$ sed -i.bak 's/old/new/g' file.txt

Combining multiple edits in one pass:

# Multiple substitutions in one command
$ sed -e 's/foo/bar/g' -e 's/baz/qux/g' -e '/^#/d' file.txt

# Same, using semicolons
$ sed 's/foo/bar/g; s/baz/qux/g; /^#/d' file.txt

# Using a script file for complex edits
$ cat fix.sed
s/foo/bar/g
s/baz/qux/g
/^#/d
/^$/d

$ sed -f fix.sed file.txt

Complete Example Session

# ============================================
# PART 1: BASIC SUBSTITUTION
# ============================================

$ cat example.txt
This is a test
And this is another line
This is the end

# Replace first occurrence per line
$ sed 's/This/That/' example.txt
That is a test
And this is another line
That is the end

# Replace all occurrences
$ sed 's/This/That/g' example.txt
That is a test
And this is another line
That is the end

# Original unchanged
$ cat example.txt
This is a test
And this is another line
This is the end

# ============================================
# PART 2: IN-PLACE EDITING
# ============================================

$ sed -i 's/This/That/g' example.txt
$ cat example.txt
That is a test
And this is another line
That is the end

# With backup
$ sed -i.bak 's/That/This/g' example.txt
$ ls example.txt*
example.txt  example.txt.bak

# ============================================
# PART 3: LINE NUMBERS
# ============================================

$ sed -n '=;p' example.txt
1
This is a test
2
And this is another line
3
This is the end

# Just line numbers
$ sed -n '=' example.txt
1
2
3

# Just specific lines
$ sed -n '1p;3p' example.txt
This is a test
This is the end

# ============================================
# PART 4: DELETION
# ============================================

# Delete lines containing "This"
$ sed '/This/d' example.txt
And this is another line

# Delete a range
$ sed '1,2d' example.txt
This is the end

# Delete empty lines
$ printf "a\n\nb\n\n\nc\n" | sed '/^$/d'
a
b
c

# Delete lines starting with #
$ printf "# comment\ncode\n# another\n" | sed '/^#/d'
code

# ============================================
# PART 5: MULTIPLE SCRIPTS
# ============================================

$ sed -e 's/This/That/g' -e 's/And/---/' example.txt
That is a test
--- this is another line
That is the end

# Same with semicolons
$ sed 's/This/That/g; s/And/---/' example.txt
That is a test
--- this is another line
That is the end

# ============================================
# PART 6: SCRIPT FILES
# ============================================

$ echo "s/This/That/g" > scriptFile
$ cat scriptFile
s/This/That/g

$ sed -f scriptFile example.txt
That is a test
And this is another line
That is the end

# Multiple commands in a script file
$ cat multi.sed
s/This/That/g
s/And/---/
/end/d

$ sed -f multi.sed example.txt
That is a test
--- this is another line

# ============================================
# PART 7: MULTIPLE FILES
# ============================================

$ cat example1.txt
This is file two
This is also here

$ sed -s 's/This/That/g' example.txt example1.txt
That is a test
And this is another line
That is the end
That is file two
That is also here

# ============================================
# PART 8: INSERT, APPEND, CHANGE
# ============================================

# Insert before line 1
$ sed '1 i\ HEADER' example.txt
HEADER
This is a test
And this is another line
This is the end

# Append after line 2
$ sed '2 a\ INSERTED' example.txt
This is a test
And this is another line
INSERTED
This is the end

# Change line 2
$ sed '2 c\ REPLACED' example.txt
This is a test
REPLACED
This is the end

# ============================================
# PART 9: RANGES AND PATTERNS
# ============================================

# Print lines 10-20
$ sed -n '10,20p' file.txt

# Print between two patterns
$ sed -n '/START/,/END/p' file.txt

# Delete between two patterns
$ sed '/START/,/END/d' file.txt

# Print only matching lines
$ sed -n '/error/p' app.log

# ============================================
# PART 10: REAL-WORLD EDITS
# ============================================

# Remove trailing whitespace
$ sed 's/[[:space:]]*$//' file.txt

# Convert DOS to Unix line endings
$ sed 's/\r$//' windows.txt > unix.txt

# Comment out a line
$ sed '/PermitRootLogin/ s/^/#/' /etc/ssh/sshd_config

# Uncomment a line
$ sed '/^#PermitRootLogin/ s/^#//' /etc/ssh/sshd_config

# Insert after a pattern
$ sed '/^Listen/a\ Listen 8080' /etc/httpd/conf/httpd.conf

# Replace a config value
$ sed 's/^port=.*/port=9090/' config.ini

# Remove HTML tags
$ sed 's/<[^>]*>//g' page.html

# ============================================
# PART 11: COMBINING WITH OTHER TOOLS
# ============================================

# Number non-empty lines
$ grep -n . file.txt

# Extract emails
$ grep -oE '[[:alnum:]._%+-]+@[[:alnum:].-]+' file.txt

# Replace and count
$ sed 's/foo/bar/g' file.txt | grep -c bar

# Chain transformations
$ cat file.txt | sed 's/foo/bar/g' | sort | uniq -c | sort -rn

Quick Reference

sed Options

OptionPurpose
-iEdit in place
-i.bakEdit in place + backup
-e SCRIPTAdd a script
-f FILERead script from file
-nSuppress auto-print
-E / -rExtended regex
-sSeparate files
-zNUL-separated lines

Substitution Flags

FlagMeaning
gGlobal
NNth occurrence
NgFrom Nth onward
pPrint if substituted
iCase-insensitive
w FILEWrite to file

Address Forms

AddressMatches
(none)Every line
NLine N
N,MRange
$Last line
/regex/Matching lines
/re1/,/re2/Pattern range
N!NOT line N

Common Commands

CommandPurpose
s/a/b/Substitute
dDelete
pPrint
a\ textAppend after
i\ textInsert before
c\ textChange line
y/abc/xyz/Transliterate
=Print line number
qQuit
nNext line
NAppend next line

sed vs Other Tools

ToolBest for
sedLine-based search & replace
grepFinding lines
awkField-based processing
trCharacter translation
cutColumn extraction

Best Practices

Do This:

# Test without -i first
sed 's/foo/bar/g' file.txt            # ✅

# Use -i.bak when editing in place
sed -i.bak 's/foo/bar/g' file.txt     # ✅

# Use -n with p for precise output
sed -n '/pattern/p' file.txt          # ✅

# Quote the script with single quotes
sed 's/foo/bar/g' file.txt            # ✅

# Use -E for extended regex
sed -E 's/(foo|bar)/X/g' file.txt     # ✅

# Use -s for independent files
sed -s 's/foo/bar/' file1 file2       # ✅

# Use script files for complex edits
sed -f fix.sed file.txt               # ✅

# Anchor patterns to avoid surprises
sed 's/^foo/bar/' file.txt            # ✅

Don’t Do This:

# Don't use -i without a backup on critical files
sed -i 's/foo/bar/g' /etc/config      # ❌ no undo

# Don't forget the /g for global replace
sed 's/foo/bar/' file.txt             # ⚠️  first occurrence only

# Don't use unescaped dots
sed 's/./X/g' file.txt                # ❌ replaces every char

# Don't forget -n with p
sed '/pattern/p' file.txt             # ❌ prints every line

# Don't use sed for field processing
sed 's/ /,/g' file.txt                # ⚠️  use awk for fields

# Don't chain too many -e scripts
sed -e 'a' -e 'b' -e 'c' ... file     # ⚠️  use a script file

# Don't ignore locale
sed 's/[A-Z]/x/g' file.txt            # ⚠️  use [[:upper:]]

Common Pitfalls

PitfallProblemSolution
Forgot -iFile unchangedAdd -i (with backup!)
Forgot /gOnly first match replacedAdd g flag
Unescaped .Matches any charEscape: \.
-n without pNo outputAdd p
BRE vs ERE+, ?, | literalUse -E
$ in shellVariable expansionUse single quotes
Multiple -iWrong orderCombine with -e
-i on symlinkReplaces the linkUse real path
Special chars in patternRegex vs literalEscape them
Trailing newline lostsed -i quirkCheck with tail -c1

Real-World Examples

1. Replace a String in a File

$ sed 's/localhost/127.0.0.1/g' config.ini > config.new
$ mv config.new config.ini

2. Edit in Place with Backup

$ sed -i.bak 's/8080/9090/g' config.ini
$ ls config.ini*
config.ini  config.ini.bak

3. Delete Commented and Empty Lines

$ sed '/^#/d; /^$/d' config.conf

4. Print Only Matching Lines

$ sed -n '/ERROR/p' app.log

5. Print a Range Between Patterns

$ sed -n '/BEGIN/,/END/p' file.txt

6. Remove Trailing Whitespace

$ sed -i 's/[[:space:]]*$//' file.txt

7. Convert Windows to Unix Line Endings

$ sed -i 's/\r$//' windows.txt

8. Comment Out a Line

$ sed -i '/PermitRootLogin/ s/^/#/' /etc/ssh/sshd_config
# Before: PermitRootLogin no
# After:  #PermitRootLogin no

9. Uncomment a Line

$ sed -i '/^#PermitRootLogin/ s/^#//' /etc/ssh/sshd_config

10. Add a Line After a Pattern

$ sed '/^\[mysqld\]/a\ port=3306' my.cnf

11. Replace a Whole Line

$ sed '/^port=/c\port=9090' config.ini

12. Number Lines

$ sed = file.txt | sed 'N; s/\n/\t/'
1	first line
2	second line
3	third line

13. Extract Emails

$ sed -nE 's/.*([[:alnum:]._%+-]+@[[:alnum:].-]+\.[[:alpha:]]{2,}).*/\1/p' file.txt

14. Remove HTML Tags

$ sed 's/<[^>]*>//g' page.html

15. Strip Quotes from a CSV Column

$ sed 's/"//g' data.csv

16. Insert a Header

$ sed '1 i\# Generated file — do not edit' output.txt

17. Delete the Last Line

$ sed '$d' file.txt

18. Print the Last Line

$ sed -n '$p' file.txt

19. Replace Tabs with Spaces

$ sed 's/\t/    /g' file.txt

20. Batch Rename References

$ sed -i 's/oldname/newname/g' *.conf

Visual: How sed Works

┌──────────────────────────────────────────────┐
│              sed 's/foo/bar/g'               │
│                                              │
│  Input line: "foo baz foo"                   │
│       │                                      │
│       ▼                                      │
│  Pattern space: "foo baz foo"                │
│       │                                      │
│       ▼                                      │
│  Apply script: s/foo/bar/g                   │
│       │                                      │
│       ▼                                      │
│  Pattern space: "bar baz bar"                │
│       │                                      │
│       ▼                                      │
│  Print (unless -n): "bar baz bar"            │
│                                              │
│  Repeat for every line                       │
│                                              │
└──────────────────────────────────────────────┘

┌──────────────────────────────────────────────┐
│           sed -n '=;p' file.txt              │
│                                              │
│  Line 1: "hello"                             │
│    =  → prints "1"                           │
│    p  → prints "hello"                       │
│                                              │
│  Line 2: "world"                             │
│    =  → prints "2"                           │
│    p  → prints "world"                       │
│                                              │
│  Output:                                     │
│    1                                         │
│    hello                                     │
│    2                                         │
│    world                                     │
│                                              │
└──────────────────────────────────────────────┘

Summary

CommandPurposeExample
sed 's/a/b/' fReplace first occurrencesed 's/This/That/' example.txt
sed 's/a/b/g' fReplace allsed 's/This/That/g' example.txt
sed 's/a/b/3' fReplace 3rd occurrencesed 's/foo/bar/3' f
sed 's/a/b/3g' fFrom 3rd onwardsed 's/foo/bar/3g' f
sed 'N s/a/b/' fReplace on line Nsed '3 s/This/That/' f
sed -i 's/a/b/g' fEdit in placesed -i 's/a/b/g' f
sed -i.bak 's/a/b/' fIn place + backupsed -i.bak 's/a/b/' f
sed -n '=;p' fLine numbers + contentsed -n '=;p' example.txt
sed '/pattern/d' fDelete matching linessed '/This/d' example.txt
sed 'N,Md' fDelete rangesed '2,4d' f
sed '/re/p' fPrint matchingsed -n '/This/p' f
sed -e 's/a/b/' -e 's/c/d/' fMultiple scriptssed -e 's/This/That/g' -e 's/And/---/' f
sed -f script fScript filesed -f scriptFile example.txt
sed -s 's/a/b/g' f1 f2Separate filessed -s 's/This/That/g' a b
sed 'N a\ text' fAppend after Nsed '2 a\ new line' f
sed 'N i\ text' fInsert before Nsed '1 i\ header' f
sed 'N c\ text' fChange line Nsed '2 c\ replaced' f
sed 'N,Mp' fPrint rangesed -n '10,20p' f
sed '/re1/,/re2/p' fPrint between patternssed -n '/S/,/E/p' f

Key takeaways:

  • sed is the stream editor — read line by line, transform, print
  • s/old/new/ is the workhorse — substitution
  • g makes it global; N targets the Nth occurrence; 3g from the 3rd onward
  • -i edits in place — always back up with -i.bak on important files
  • -n suppresses auto-print — pair it with p to print only what you want
  • -e adds a script; -f reads from a file — use them for multiple edits
  • -s treats multiple files as separate streams
  • Address lines with N, N,M, /regex/, or /re1/,/re2/
  • Commands: d delete, p print, a\** append, **i\ insert, c\** change, **y///** transliterate, **= line number
  • Use -E for extended regex (+, ?, |, ())
  • For word-level work, sed beats tr. For field-level work, awk beats sed.
  • Test without -i first, quote your scripts, and anchor patterns to avoid surprises

Remember: sed is the most-used text tool in shell scripting after grep. Learn s///g, -n 'p', /pattern/d, -i.bak, and -e — those five cover 90% of real-world usage. Use -E when your regex needs +, ?, or |. Never run -i on a file you can’t afford to lose without a backup. And when the job is about characters, reach for tr; when it’s about fields, reach for awk; when it’s about lines and patterns, sed is the right tool.


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!