Finding and Replacing Text with sed

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 108 of 205

Finding and replacing text is the job sed is best known for. Its substitute command, s, searches each line for a regular expression and replaces the matched text with new text. Scripts use it to update configuration values, rename paths, clean up command output, reformat dates, hide sensitive values in logs and much more, all without opening an editor.

Lesson 106 introduced sed alongside grep and awk. This lesson covers the s command in depth: its flags, regular expressions, captured groups, addresses that limit which lines change, editing files in place, and safely using shell variables in a substitution.

The Substitute Command

The basic form is:

sed 's/PATTERN/REPLACEMENT/FLAGS' file
PartMeaning
sThe substitute command
/The delimiter that separates the parts (any character can be used, see below)
PATTERNA regular expression to search for
REPLACEMENTThe text that replaces the match
FLAGSOptional letters or numbers that change how the substitution works

sed reads one line at a time into an internal buffer called the pattern space, applies the command, prints the result, and moves to the next line. The input file is not changed unless -i is used.

Replacing the First Match or Every Match

Without flags, s replaces only the first match on each line:

echo 'cat cat cat' | sed 's/cat/dog/'
dog cat cat

The g (global) flag replaces every match on the line:

echo 'cat cat cat' | sed 's/cat/dog/g'
dog dog dog

A number replaces only that occurrence, and in GNU sed a number combined with g replaces that occurrence and all later ones:

echo 'cat cat cat' | sed 's/cat/dog/2'
echo 'cat cat cat' | sed 's/cat/dog/2g'
cat dog cat
cat dog dog

GNU sed also accepts I to ignore case:

echo 'Cat CAT cat' | sed 's/cat/dog/Ig'
dog dog dog

I is a GNU extension. BSD sed on macOS does not support it.

The Pattern Is a Regular Expression

The pattern is not plain text. Characters such as ., *, [, ^ and $ have special meanings. A dot matches any single character:

echo 'v1.2 v1x2' | sed 's/1.2/ONE/g'
echo 'v1.2 v1x2' | sed 's/1\.2/ONE/g'
vONE vONE
vONE v1x2

The first command also changed 1x2, because . matched the x. A backslash before the dot makes it a literal dot.

^ anchors the match to the start of the line and $ to the end. Anchoring prevents accidental partial matches:

printf 'port=80\nexport=1\n' | sed 's/^port=/PORT=/'
PORT=80
export=1

Without ^, a pattern port= would also match inside export=.

Basic and Extended Regular Expressions

By default sed uses basic regular expressions (BRE). In BRE, +, ?, |, (, ), { and } are ordinary characters, and their special meanings need a backslash. The -E option switches to extended regular expressions (ERE), where they are special without a backslash:

echo 'aaa b' | sed 's/a+/X/'      # BRE: + is a literal plus sign
echo 'aaa b' | sed 's/a\+/X/'     # GNU BRE: \+ means one or more
echo 'aaa b' | sed -E 's/a+/X/'   # ERE: + means one or more
aaa b
X b
X b

The first command found no literal + and changed nothing. 0 in BRE is a GNU extension; -E is the portable way, supported by GNU sed and BSD sed. Intervals work in both styles:

echo 'aaaa' | sed 's/a\{2\}/X/'
echo 'aaaa' | sed -E 's/a{2}/X/'

Both print Xaa. This lesson uses -E whenever a pattern needs groups or repetition operators, because it is easier to read.

Greedy Matching

* and + match as much as possible. A pattern meant to remove one HTML tag can remove far more:

echo '<b>bold</b> and <i>it</i>' | sed 's/<.*>//'
echo '<b>bold</b> and <i>it</i>' | sed 's/<[^>]*>//g'

bold and it

<.*> matched from the first < to the very last >, so the whole line disappeared and an empty line was printed. <[^>]*> means "a <, then any characters that are not >, then >", which matches one tag at a time. sed has no non-greedy operator, so negated character classes like [^>] are the standard technique.

Choosing a Different Delimiter

Paths contain slashes, which collide with the default delimiter. Every slash in the pattern or replacement must then be escaped:

echo '/var/log/app' | sed 's/\/var\/log/\/srv\/logs/'

The character right after s becomes the delimiter, so any other character avoids the escaping:

echo '/var/log/app' | sed 's|/var/log|/srv/logs|'
echo '/var/log/app' | sed 's#/var/log#/srv/logs#'

All three commands print /srv/logs/app. |, #, : and , are common choices; pick one that does not appear in the text.

Using the Match in the Replacement

The & Character

In the replacement, & stands for the whole matched text:

echo 'error 42' | sed 's/[0-9][0-9]*/[&]/'
error [42]

To insert a literal ampersand, escape it as \&:

echo 'AT&T' | sed 's/AT/A\&T: &/'
A&T: AT&T

Captured Groups

Parentheses capture parts of the match, and \1, \2 and so on refer to them in the replacement, numbered by their opening parenthesis from left to right. This reorders a date from year-month-day to day.month.year:

echo '2026-11-20' | sed -E 's/([0-9]+)-([0-9]+)-([0-9]+)/\3.\2.\1/'
20.11.2026

The same command in basic syntax needs backslashes before the parentheses, and here the replacement also contains slashes that must be escaped:

echo '2026-11-20' | sed 's/\([0-9]*\)-\([0-9]*\)-\([0-9]*\)/\3\/\2\/\1/'
20/11/2026

Groups make swapping parts of a line simple:

echo 'Silva, Ana' | sed -E 's/([^,]+), (.+)/\2 \1/'
Ana Silva

([^,]+) captures everything up to the comma, , matches the comma and space, and (.+) captures the rest.

Special Characters in the Replacement

GNU sed understands \n (newline) and \t (tab) in patterns and replacements:

echo 'a,b,c' | sed 's/,/\n/g'
printf 'a\tb\n' | sed 's/\t/ | /'
a
b
c
a | b

GNU sed can also change case in the replacement with \U (uppercase from here), \L (lowercase from here), \u (next character uppercase) and \l (next character lowercase):

echo 'hello world' | sed 's/\w\+/\u&/g'
echo 'Error: disk' | sed 's/.*/\U&/'
echo 'key=VALUE' | sed -E 's/(.*)=(.*)/\1=\L\2/'
Hello World
ERROR: DISK
key=value

\w, \n in the replacement, and the case conversions are GNU extensions.

Limiting Which Lines Change: Addresses

An address before s restricts the substitution to certain lines. The examples use app.conf:

# App settings
host=localhost
port=8080
debug=true
log_dir=/var/log/app
  name = demo app  

timeout=30

(The name line has two spaces before and after it, and the line before timeout is empty.)

AddressSelects
3Line 3
$The last line
2,4Lines 2 to 4
/regex/Lines matching the regex
/start/,/end/From a line matching start through the next line matching end
addr!Every line that does not match the address

A pattern address is the safest way to change one setting, because the substitution only runs on the right line:

sed '/^port=/s/8080/9090/' app.conf | grep port
port=9090

Line numbers and ranges:

seq 1 6 | sed '2,4s/^/> /'
seq 1 3 | sed '$s/$/ (last)/'
1
> 2
> 3
> 4
5
6
1
2
3 (last)

In $s/$/ (last)/, the first $ is the address (last line) and the second is the regular expression anchor (end of line). Replacing ^ or $ inserts text at the start or end of a line.

A range between two patterns is useful for blocks of text:

printf 'x\nSTART\n1\n2\nEND\ny\n' | sed '/START/,/END/s/^/  /'
x
  START
  1
  2
  END
y

! inverts an address. This changes = to : on every line except comments:

sed '/^#/!s/=/: /' app.conf
# App settings
host: localhost
port: 8080
debug: true
log_dir: /var/log/app
  name :  demo app  

timeout: 30

When an address uses the same pattern as the substitution, an empty pattern // reuses the last regular expression:

echo 'cat dog cat' | sed '/cat/s//COW/g'
COW dog COW

Several Commands at Once

Commands can be separated by semicolons or given as separate -e options. Both commands below print a b c:

echo 'a-b_c' | sed 's/-/ /; s/_/ /'
echo 'a-b_c' | sed -e 's/-/ /' -e 's/_/ /'

Each line passes through the commands in order, so later commands see the result of earlier ones.

Practical Substitutions

Updating a Configuration Value

Capture the key and replace everything after it:

sed 's/^\(port=\).*/\19090/' app.conf | grep port
sed -E 's/^(timeout=).*/\160/' app.conf | grep timeout
port=9090
timeout=60

\19090 is read as group 1 followed by the text 9090; sed only supports \1 to \9, so there is no ambiguity.

Trimming Whitespace

sed 's/^[[:space:]]*//; s/[[:space:]]*$//' app.conf

The first command removes leading spaces and tabs, the second removes trailing ones. The name line becomes name = demo app with nothing before or after it. [[:space:]] is a POSIX character class that matches spaces, tabs and other whitespace.

Masking Sensitive Values

sed -E 's/user=[a-z]+/user=***/' app.log | head -2
2026-11-20 08:15:02 INFO web01 login user=*** ms=120
2026-11-20 08:15:09 WARN web02 slow_query user=*** ms=950

Printing Only Changed Lines

With -n, nothing is printed automatically, and the p flag prints a line only if the substitution happened:

sed -n 's/true/false/p' app.conf
debug=false

Editing Files in Place with -i

By default sed writes to standard output and leaves the file unchanged. GNU sed's -i option writes the result back to the file:

sed -i 's/^debug=true/debug=false/' work.conf
grep debug work.conf
debug=false

A suffix after -i keeps a backup of the original:

sed -i.bak 's/^port=.*/port=9090/' work2.conf
grep port work2.conf work2.conf.bak
work2.conf:port=9090
work2.conf.bak:port=8080

-i does not edit the file directly. GNU sed writes the output to a new temporary file and then renames it over the original. Two consequences follow:

  • The file gets a new inode. In the test, a hard link made before the edit still showed port=8080 after sed -i changed the file to port=9999, and programs holding the file open still see the old version.
  • If the name is a symbolic link, the link is replaced by a regular file. In the test, sed -i on link.conf left a regular file named link.conf, and the original target was not changed. GNU sed's --follow-symlinks option edits the target instead.

Without any file name, -i fails:

sed: no input files

with exit status 4.

On macOS, BSD sed requires an argument after -i, even an empty one: sed -i '' 's/a/b/' file. The GNU form sed -i 's/a/b/' file treats the program as a backup suffix there. Scripts meant for both systems often use -i.bak (which both accept) and remove the backup afterward.

Previewing Before Editing

A safe workflow is to compare the original with sed's output before using -i. diff with process substitution (lesson 151) shows exactly what would change:

diff app.conf <(sed 's/^port=.*/port=9090/' app.conf)
3c3
< port=8080
---
> port=9090

diff returns status 1 when it finds differences and 0 when there are none.

Using Shell Variables in a Substitution

To insert a Bash variable, the sed program must be in double quotes so Bash expands the variable. This creates two problems: the delimiter, and special characters in the value.

The Delimiter Problem

If the value contains the delimiter, the command breaks:

new=/srv/data
echo 'dir=/tmp' | sed "s/\/tmp/$new/"
sed: -e expression #1, char 10: unknown option to `s'

After expansion, sed receives s/\/tmp//srv/data/, and the slashes in /srv/data end the replacement early. A delimiter that cannot appear in the value fixes it:

echo 'dir=/tmp' | sed "s|/tmp|$new|"
dir=/srv/data

The Special Character Problem

Even with a safe delimiter, characters that are special in the replacement are interpreted. An & in the value turns into the matched text:

repl='R&D'
echo 'team=X' | sed "s|X|$repl|"
team=RXD

For values that might contain any character, escape them first. In the replacement, only &, the backslash and the delimiter are special:

esc=$(printf '%s' "$repl" | sed 's/[&|\\]/\\&/g')
echo "esc=$esc"
echo 'team=X' | sed "s|X|$esc|"
esc=R\&D
team=R&D

The helper sed command puts a backslash before each &, | and ``. The same idea works for the pattern side, where the regular expression characters must be escaped:

pat='1.2'
epat=$(printf '%s' "$pat" | sed 's/[]\/$*.^[]/\\&/g')
echo "epat=$epat"
echo 'v1.2 v1x2' | sed "s/$epat/ONE/g"
epat=1\.2
vONE v1x2

The bracket expression []\/$*.^[] lists the BRE special characters ], /, $, *, ., ^ and [. A value containing a newline cannot be handled this way. When replacement text comes from users or files and can contain anything, awk with -v variables and its index and substr functions, or a language like Python, is often a more reliable choice.

Other Line-Level Commands

The c command replaces whole lines selected by an address, which is sometimes simpler than a substitution:

seq 1 3 | sed '2c\two'
1
two
3

Writing the new text on the same line as `c` is a GNU convenience; the POSIX form puts the text on the next line of the script.

GNU sed also accepts the step address first~step, for example 0~3 for every third line:

seq 1 10 | sed -n '0~3p'
3
6
9

The examples in this lesson were run with GNU sed 4.9 in Bash 5.2.21. Features marked as GNU extensions (I, 2g, 0, \w, \n and \t in replacements, \U and \L, -i without an argument, --follow-symlinks, first~step) may be missing or behave differently in BSD sed.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Finding and Replacing Text with sed and get answers drawn from it.

Signed-in readers only.