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 commandssedwill executeinputfile— the file(s) to process (or stdin if omitted)
Common options:
| Option | Purpose |
|---|---|
-i | Edit files in place (saves changes to the original) |
-e SCRIPT | Add a script to the list of editing commands (for multiple scripts) |
-f FILE | Read editing commands from FILE |
-n | Suppress automatic printing of the pattern space |
-E / -r | Use extended regex |
-s | Treat files as separate streams (not one long stream) |
-z | Use 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:
-iedits the file in place with no undo. Test your script without-ifirst, or always use-i.bakto 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).
| Script | Meaning |
|---|---|
s/what/with/ | Substitute what with with |
s/what/with/3 | Substitute only the 3rd occurrence on each line |
s/what/with/3g | Substitute from the 3rd occurrence onward |
s/what/with/g | Substitute all occurrences (global) |
3 s/what/with/ | Substitute on line 3 only |
n,md | Delete lines from n to m |
n a\ text | Append text after line n |
/pattern/p | Print lines matching pattern |
Address forms:
| Address | Matches |
|---|---|
| (none) | Every line |
N | Line N |
N,M | Lines N through M |
$ | Last line |
/regex/ | Lines matching regex |
/regex1/,/regex2/ | Range between two patterns |
N! | NOT line N |
Substitution flags:
| Flag | Meaning |
|---|---|
g | Global — all occurrences on the line |
N | Replace only the Nth occurrence |
Ng | Replace from the Nth occurrence onward |
p | Print the line if a substitution was made |
i | Case-insensitive match |
w FILE | Write 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:
| Command | Purpose |
|---|---|
p | Print the current line |
d | Delete the current line |
a\ text | Append text after the line |
i\ text | Insert text before the line |
c\ text | Change (replace) the line |
y/abc/xyz/ | Transliterate characters (like tr) |
q | Quit after the current line |
= | Print the line number |
n | Read 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
| Option | Purpose |
|---|---|
-i | Edit in place |
-i.bak | Edit in place + backup |
-e SCRIPT | Add a script |
-f FILE | Read script from file |
-n | Suppress auto-print |
-E / -r | Extended regex |
-s | Separate files |
-z | NUL-separated lines |
Substitution Flags
| Flag | Meaning |
|---|---|
g | Global |
N | Nth occurrence |
Ng | From Nth onward |
p | Print if substituted |
i | Case-insensitive |
w FILE | Write to file |
Address Forms
| Address | Matches |
|---|---|
| (none) | Every line |
N | Line N |
N,M | Range |
$ | Last line |
/regex/ | Matching lines |
/re1/,/re2/ | Pattern range |
N! | NOT line N |
Common Commands
| Command | Purpose |
|---|---|
s/a/b/ | Substitute |
d | Delete |
p | |
a\ text | Append after |
i\ text | Insert before |
c\ text | Change line |
y/abc/xyz/ | Transliterate |
= | Print line number |
q | Quit |
n | Next line |
N | Append next line |
sed vs Other Tools
| Tool | Best for |
|---|---|
sed | Line-based search & replace |
grep | Finding lines |
awk | Field-based processing |
tr | Character translation |
cut | Column 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
| Pitfall | Problem | Solution |
|---|---|---|
Forgot -i | File unchanged | Add -i (with backup!) |
Forgot /g | Only first match replaced | Add g flag |
Unescaped . | Matches any char | Escape: \. |
-n without p | No output | Add p |
| BRE vs ERE | +, ?, | literal | Use -E |
$ in shell | Variable expansion | Use single quotes |
Multiple -i | Wrong order | Combine with -e |
-i on symlink | Replaces the link | Use real path |
| Special chars in pattern | Regex vs literal | Escape them |
| Trailing newline lost | sed -i quirk | Check 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
| Command | Purpose | Example |
|---|---|---|
sed 's/a/b/' f | Replace first occurrence | sed 's/This/That/' example.txt |
sed 's/a/b/g' f | Replace all | sed 's/This/That/g' example.txt |
sed 's/a/b/3' f | Replace 3rd occurrence | sed 's/foo/bar/3' f |
sed 's/a/b/3g' f | From 3rd onward | sed 's/foo/bar/3g' f |
sed 'N s/a/b/' f | Replace on line N | sed '3 s/This/That/' f |
sed -i 's/a/b/g' f | Edit in place | sed -i 's/a/b/g' f |
sed -i.bak 's/a/b/' f | In place + backup | sed -i.bak 's/a/b/' f |
sed -n '=;p' f | Line numbers + content | sed -n '=;p' example.txt |
sed '/pattern/d' f | Delete matching lines | sed '/This/d' example.txt |
sed 'N,Md' f | Delete range | sed '2,4d' f |
sed '/re/p' f | Print matching | sed -n '/This/p' f |
sed -e 's/a/b/' -e 's/c/d/' f | Multiple scripts | sed -e 's/This/That/g' -e 's/And/---/' f |
sed -f script f | Script file | sed -f scriptFile example.txt |
sed -s 's/a/b/g' f1 f2 | Separate files | sed -s 's/This/That/g' a b |
sed 'N a\ text' f | Append after N | sed '2 a\ new line' f |
sed 'N i\ text' f | Insert before N | sed '1 i\ header' f |
sed 'N c\ text' f | Change line N | sed '2 c\ replaced' f |
sed 'N,Mp' f | Print range | sed -n '10,20p' f |
sed '/re1/,/re2/p' f | Print between patterns | sed -n '/S/,/E/p' f |
Key takeaways:
sedis the stream editor — read line by line, transform, prints/old/new/is the workhorse — substitutiongmakes it global;Ntargets the Nth occurrence;3gfrom the 3rd onward-iedits in place — always back up with-i.bakon important files-nsuppresses auto-print — pair it withpto print only what you want-eadds a script;-freads from a file — use them for multiple edits-streats multiple files as separate streams- Address lines with
N,N,M,/regex/, or/re1/,/re2/ - Commands:
ddelete,pprint,a\** append, **i\insert,c\** change, **y///** transliterate, **=line number - Use
-Efor extended regex (+,?,|,()) - For word-level work,
sedbeatstr. For field-level work,awkbeatssed. - Test without
-ifirst, 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!