logo
search
list

Table of Content

Basic Syntax
Substitute: s/// Flags You Actually Use
Edit a File in Place (-i)
Pick a Delimiter When Paths Have /
Use Shell Variables in Sed (Classic Ask Ubuntu Gotcha)
Addresses: Act on One Line or a Range
Delete, Insert, Append
Extended Regular Expressions (-E / -r)
Sed in Pipelines
Common Mistakes
When to Use Sed
Quick Cheat Sheet
From Stream Edits to Shareable Documents
FAQ

Sed Command in Linux: Replace, Edit & Transform Text (Ubuntu)

Posted by Algirdas Jasaitis

calendar

2026-07-27

views

879

likes

5

The sed command in Linux is a stream editor: it reads text line by line, applies editing commands, and writes the result to standard output (or back to a file with -i). On Ubuntu, sed is the GNU version from the essential sed package. Official docs describe it as a one-pass filter for pipelines and scripted edits—especially useful for find-and-replace, deleting lines, and small config tweaks without opening a full editor.

Check your version:

sed --version
man sed

Official reference: Ubuntu man page sed(1). If you already know your goal, jump to: substitute, in-place edit, variables, delimiters, or delete/insert. For finding lines only, see grep; for columns, see awk.

Concept illustration of the Linux sed stream editor substituting text in a terminal (s/foo/bar/g)
Sed reads a stream, applies edits like s/old/new/g, and writes the result—preview on stdout, then use -i when you are ready to change the file.

For a broader Ubuntu terminal quick reference, see the Linux commands cheat sheet.

Basic Syntax

sed [options] 'script' [file...]

If you omit a file, sed reads stdin (great in pipes). With no -e/-f, the first non-option argument is the script.

Most people start with substitute (s):

sed 's/old/new/' file.txt

That replaces the first match of old on each line. Output goes to the terminal; the original file is unchanged unless you use -i.

Substitute: s/// Flags You Actually Use

# First match per line
sed 's/foo/bar/' notes.txt

# All matches on each line
sed 's/foo/bar/g' notes.txt

# Case-insensitive (GNU sed)
sed 's/foo/bar/gi' notes.txt

# Print only lines where a substitution happened (with -n)
sed -n 's/foo/bar/p' notes.txt

In the replacement:

  • & means “the whole match”
  • \1\9 are capture groups (use \(...\) in basic regex, or (...) with -E)
echo 'error 42' | sed 's/[0-9]\+/(&)/'
# error (42)

Edit a File in Place (-i)

GNU sed can rewrite files with -i. Ask Ubuntu answers often stress: preview without -i first, then edit.

# Preview
sed 's/# autologin=dgod/autologin=ubuntu/' /path/to/file

# Write the file (GNU sed)
sed -i 's/# autologin=dgod/autologin=ubuntu/' /path/to/file

# Safer: keep a backup
sed -i.bak 's/foo/bar/g' config.conf
# creates config.conf.bak

From the Ubuntu man page: -i[SUFFIX] edits in place and makes a backup if SUFFIX is supplied.

Pick a Delimiter When Paths Have /

You are not stuck with /. Sed treats the first character after s as the separator. On Ask Ubuntu, people often use # or | for URLs and paths so you do not escape every slash:

# Painful
sed 's/https:\/\/example.com\/old/https:\/\/example.com\/new/' file

# Clearer
sed 's|https://example.com/old|https://example.com/new|' file
sed 's#/usr/local#/opt#' paths.txt

Same idea: /bin/sed -e 's#abc#zzz#g' — the # is just a delimiter, not a special “mode.”

Use Shell Variables in Sed (Classic Ask Ubuntu Gotcha)

Single quotes stop the shell from expanding $var. Use double quotes (or mix quotes):

var1=QQ
# Wrong: looks for literal $var1
sed -i 's/$var1/ZZ/g' "$file"

# Right
sed -i "s/$var1/ZZ/g" "$file"

If the variable may contain /, change the delimiter:

sed -i "s|$var|replacement|g" file_name

When the pattern has many shell metacharacters, Ask Ubuntu’s accepted pattern is: single-quote the fixed parts, double-quote the variable:

sed -i 's,'"$pattern"',Say hurrah to &: \0/,' "$file"

Addresses: Act on One Line or a Range

Commands can take an address (line number, $ for last line, or /regex/):

# Only line 3
sed '3s/foo/bar/' file.txt

# Lines 10 through 20
sed '10,20s/foo/bar/g' file.txt

# Lines matching a pattern
sed '/^#/d' file.txt          # delete comment lines
sed -n '/ERROR/p' app.log     # print matching lines only (-n suppresses default print)

Replace a known config line (Ask Ubuntu-style):

sed -i 's/# autologin=dgod/autologin=ubuntu/' /path/to/file

Delete, Insert, Append

# Delete lines matching a pattern
sed '/^DEBUG/d' app.log

# Delete line 1
sed '1d' file.txt

# Insert text before a matching line (GNU: \n for newlines)
sed -i '/the specific line/i #this\n##is my\ntext' foo

# Or with trailing backslashes on each inserted line
sed -i '/the specific line/i\
#this\
##is my\
text' file

a appends after the address; i inserts before it. For large blocks or command output, Ask Ubuntu also suggests r (read a file) or switching to awk when the job is awkward in sed.

Extended Regular Expressions (-E / -r)

By default, sed uses basic regular expressions (BRE). For extended regex (ERE), use -E (preferred for portability) or -r:

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

Note: GNU sed is not a full PCRE engine. Ask Ubuntu threads about “sed with PCRE like grep -P” usually end with: use perl -pe or grep -P when you need Perl-style regex.

Sed in Pipelines

dmesg | sed -n '/error/Ip'
cat report.txt | sed 's/\r$//'          # strip CR from Windows line endings
printf 'a\nb\nc\n' | sed 's/^/> /'      # prefix each line

Combine with earlier tools: grep to find, sed to rewrite, awk when you need fields and logic.

Common Mistakes

MistakeFix
Expecting the file to changeAdd -i only after previewing stdout
$var not expandingUse "s/$var/.../" not single quotes alone
Broken paths with /Use s|...|...| or s#...#...#
Only first match replacedAdd the g flag
Thinking sed matches “strings” onlyPatterns are always regex—escape . * [ ] etc. when you mean literals
Need PCREPrefer perl -pe or another tool

Backup tip: sed -i.bak '...' file before mass edits on configs.

When to Use Sed

Reach for sed when you need stream find-and-replace, delete/insert lines, or simple transforms. Use grep to find or filter lines, and awk when the job is about fields, sums, or small reports. A common pipeline is grepsed → redirect.

Quick Cheat Sheet

sed 's/a/b/' f              # first a→b per line
sed 's/a/b/g' f             # all a→b per line
sed -i 's/a/b/g' f          # edit file in place
sed -i.bak 's/a/b/g' f      # in place + backup
sed -n '/pat/p' f           # print matching lines
sed '/pat/d' f              # delete matching lines
sed '3d' f                  # delete line 3
sed -E 's/(x|y)/z/g' f      # extended regex
sed "s|$old|$new|g" f       # variables + safe delimiter

From Stream Edits to Shareable Documents

sed is ideal for fast stream edits and config changes. After the transform is finished, you may still need to document what changed or send a readable summary to someone outside the shell.

WPS Office for Linux makes that handoff easier with Writer for change notes, Spreadsheet for replacement lists, and PDF export for a fixed review copy.

WPS Office Writer on a Linux desktop editing an incident report DOCX with a familiar ribbon toolbar
WPS Writer on Linux: turn setup notes, terminal findings, and troubleshooting steps into a DOCX or PDF that teammates can open easily.
What you need nextWhat WPS gives you
Document text transformations after terminal editsStrong .docx / .xlsx / .pptx layout fidelity when files move between Linux, Windows, and macOS
One place for notes, sheets, slides, and PDFsFree core suite: Writer, Spreadsheet, Presentation, plus PDF view/edit/convert tools
A familiar desktop UI for switchersRibbon-style apps with a lighter footprint than many heavy suites
A trusted install pathOfficial DEB (Ubuntu/Debian/Mint) and RPM packages from the vendor

Get the current package from the official WPS Office for Linux download page, install it locally with sudo apt install ./wps-office_VERSION_amd64.deb, then move the final results from stdout into a DOCX or PDF when the audience is no longer just the terminal.

FAQ

Does sed modify the file by default?
No. It prints to stdout. Use -i (optionally with a backup suffix) to rewrite the file.

How do I replace only on a specific line?
Address it: sed '12s/old/new/' file or match content: sed '/pattern/s/old/new/' file.

Why didn’t my variable work in sed?
Single quotes pass $name literally. Use double quotes or concatenate quoted pieces so the shell expands the variable.

Can sed do multiline replace easily?
Simple cases work with N, hold space, or GNU extensions; for heavy multiline or JSON/XML, prefer a dedicated tool or a short script.

Where is the official documentation?
Run man sed or see the Ubuntu sed(1) man page.

Algirdas Jasaitis

15 years of office industry experience, tech lover and copywriter. Follow me for product reviews, comparisons, and recommendations for new apps and software.