Host Your Own AI Agent with OpenClaw - Free 1-Click Setup!

How to Use the Linux sed Command in 2026

Every sysadmin hits the same wall eventually: you’ve got 400 config files, one wrong IP address in all of them, and exactly zero interest in opening each one by hand. That’s where the sed command earns its keep.

The Linux sed command (short for stream editor) lets you find, replace, insert, and delete text in files straight from the terminal. No GUI, no text editor, no clicking through menus. Pipe in data, get transformed output. It handles regex patterns, works on piped input, and processes files of any size without breaking a sweat.

This guide covers sed command syntax, options, practical examples, and real-world use cases. If you’ve never touched sed, you’ll be dangerous by the end. If you already know the basics, the batch processing and backreference sections should fill in the gaps.

Sed works on a simple loop: read a line, apply your commands, output the result, repeat. It never loads the entire file into memory, which means it can chew through multi-gigabyte log files without flinching. That single-line-at-a-time approach is what makes it so efficient for scripted automation and one of the reasons it’s survived since the 1970s.

sed Command Syntax and Options

The general sed command syntax looks like this:

sed [options] 'script' filename

The script portion holds the subcommand, search pattern, replacement string, and flags. These are wrapped in single quotes and separated by a delimiter, usually a forward slash (/). You can also use backslash or pipe as delimiters when your pattern contains slashes.

Here are the most common sed options you’ll actually use:

  • -i — overwrites the original file in place. The single most dangerous and useful flag.
  • -n — suppresses automatic printing. Only lines you explicitly print with p will show up.
  • -e — lets you chain multiple commands in one sed call.
  • -f — reads commands from an external script file.
  • –help — prints usage information.
  • –debug — annotates execution in the terminal.
  • -b — opens files in binary mode.
  • -l — sets line-wrap length for the l command.

The workhorse is the s (substitute) command. Its syntax:

's/regex_pattern/replacement/flags'

The sed flags that modify substitution behavior:

  • g — global replacement. Hits every match in the line, not just the first.
  • p — prints the modified line as extra output.
  • i — case-insensitive matching.
  • Number — replace only the nth occurrence (e.g., 2 replaces the second match).

You can combine flags. The gi flag does a global, case-insensitive substitution.

One thing worth knowing: the delimiter doesn’t have to be a slash. If you’re working with file paths or URLs that are full of slashes, use a pipe or comma instead. sed 's|/old/path|/new/path|g' reads much cleaner than escaping every slash. Pick whatever character doesn’t appear in your search or replacement strings.

How to Install sed on Linux

Odds are, sed is already on your system. It ships with practically every Linux distribution. But if you’re running some stripped-down container image or minimal install, here’s how to use sed after getting it installed:

Update your package list:

sudo apt-get update

Install the sed package:

sudo apt-get install sed

Verify the installation:

sed --version

If that prints a version number, you’re set. On RHEL/CentOS-based distros, swap apt-get for yum or dnf. The sed stream editor package name stays the same across distros.

On Arch Linux, sed is part of the base group and should already be present. On Alpine (common in Docker containers), use apk add sed. If you’re running macOS, the default sed is the BSD version, which behaves slightly differently from GNU sed. Most tutorials online assume GNU sed, so install it via Homebrew with brew install gnu-sed to avoid headaches.

sed Command Examples

Here are 10 practical sed command examples that cover the operations you’ll use daily. Every command below leaves the original file untouched. Add -i when you’re ready to commit changes for real.

Search and Replace a String With sed

The most common use of sed. The sed search and replace syntax is dead simple:

sed 's/old_string/new_string/' myfilename.txt

Suppose you’ve got a file called scenery.txt and need to swap “images” for “photos”:

sed 's/images/photos/' scenery.txt

This sed find and replace hits only the first match on each line. If your search string contains slashes, switch to a different delimiter:

sed 's|/usr/local|/opt|' config.txt

The original file stays untouched. Sed sends results to stdout by default. Once you’ve confirmed the output looks right, tack on -i to write changes back to the file. Always test first, commit second.

Replace the nth Occurrence in a Line

When a word appears multiple times on the same line and you only want to change one specific instance, add a number flag:

sed 's/old_string/new_string/2' myfilename.txt

The 2 tells sed to skip the first match and only sed replace nth occurrence. For example, replace the first “music” with “song”:

sed 's/music/song/1' playlist.txt

Replace All Occurrences With the g Flag

Without the g flag, sed stops after the first match per line. The sed global replace flag fixes that:

sed 's/eagle/falcon/g' birds.txt

Every “eagle” on every line becomes “falcon.” This is what most people actually want when they think of find-and-replace. Without the g flag, sed only touches the first match per line and moves on. That default behavior trips up beginners constantly. If your substitution seems to miss some matches, the g flag is almost certainly what you’re missing.

Replace From nth to All Occurrences

You can combine a number with the g flag to start replacing from a specific occurrence onward:

sed 's/pisces/aquarius/2g' astrology.txt

This skips the first “pisces” on each line and replaces from the second occurrence through the last. Niche, but handy when your data has a predictable structure.

Parenthesize the First Character of Words

A fun sed regex trick using extended regular expressions and a sed capture group:

echo "An example of the sed command" | sed -E 's/(\b\w)/(\1)/g'

Output: (A)n (e)xample (o)f (t)he (s)ed (c)ommand

To process a file instead of piped input, drop the echo and add the filename at the end.

Replace a String on a Specific Line

Prefix the s command with a line number to sed replace line content at that exact position:

sed '2s/cake/bread/' foods.txt

Only line 2 is affected. Everything else passes through unchanged. This is useful when you know exactly which line holds the value you need to fix.

Print Replaced Lines With the /p Flag

The p flag duplicates any modified line in the output:

sed 's/phones/tablets/p' gadgets.txt

Lines that weren’t modified print once as normal. Modified lines print twice: once as output, once as the extra print. This is useful for quickly spotting which lines your pattern actually hit.

Replace a String in a Range of Lines

You can restrict a substitution to a specific line range. This is a targeted sed replace in file approach:

sed '3,5 s/germany/france/' countries.txt

Only lines 3 through 5 are processed. Lines before and after are left alone. Good for editing a known block in a config file.

Print Only the Replaced Lines

Combine sed -n option with p to suppress all default output and show only modified lines:

sed -n 's/green/blue/3p' colors.txt

Quiet mode. Only the lines where a substitution actually happened get printed. Perfect for confirming your pattern works before running with -i.

Delete Lines From a File Using sed

The d command is the sed delete line tool. Remove a single line by number:

sed '1d' cities.txt

Delete a range:

sed '1,3d' cars.txt

To delete from line 2 to the end of file:

Delete the last line:

sed '$d' filename.txt

Delete all lines matching a pattern (sed delete lines by regex):

sed '/oabo/d' filestrings.txt

This removes every line containing “oabo” from the output. Combine it with -i and you’ve got a one-liner that cleans up a file in milliseconds.

A common real-world use: stripping comment lines from config files before processing them. Something like sed ‘/^#/d’ config.conf removes all lines that start with a hash. You can also chain multiple delete patterns using the -e flag to clean up several patterns in one pass.

sed Command Use Cases

The examples above cover the syntax. Now let’s look at how to use sed in real-world server administration tasks.

sed for Batch File Processing

Two approaches. First, list multiple files explicitly:

sed 's/old_string/new_string/g' file1.txt file2.txt file3.txt

Second, use find to scan a directory. This is the real power move for sed replace in file at scale:

find /etc/myapp/ -type f -exec sed -i 's/old_string/new_string/g' {} \;

Fair warning: the -i flag here rewrites files in place. Create backups first. You can pass -i.bak to have sed create a backup of each file automatically before modifying it.

This is where sed really shines for sysadmins. Imagine you’ve migrated a service to a new IP and need to update the address in every Nginx config, every cron job, and every script that references it. One find+sed command and you’re done in seconds. Manual editing would take the rest of your afternoon.

sed for Log File Analysis

Sed isn’t just for editing. It’s a decent sed regex extraction tool. Pull specific patterns from log files and redirect to a new file:

sed -n 's/Error: \(.*\)/\1/p' logfile.log > error_logs.txt

That command finds every line starting with “Error:” and extracts everything after it. Change the pattern to match timestamps, IP addresses, or whatever you’re hunting for. Not as powerful as awk or grep for complex parsing, but for quick extraction jobs, sed gets it done in one line.

A practical pattern: pulling all 404 status codes from an access log. Or extracting just the timestamps from entries that mention a specific service. Sed’s real advantage here is the ability to both find and transform in one step, rather than grep-ing for matches and then cutting or awk-ing the fields you need.

sed for HTML and XML Tag Editing

Need to change an attribute across a bunch of HTML files? sed replace string handles markup tags just fine:

sed 's/\(<h[1-6].*color:\) [^;]*/\1 black/g' webpage.html

That finds any h1 through h6 tag with an inline color style and swaps the value to black. XML works the same way. Just watch your angle brackets and escape them properly.

This approach works well for quick fixes across static HTML files. If you need to change a class name on every div, update a CDN URL in script tags, or strip deprecated attributes from legacy markup, sed handles it without pulling in a full XML parser. That said, for deeply nested or complex XML structures, a proper parsing tool like xmlstarlet is the safer bet. Sed treats everything as plain text, so it won’t warn you if your regex accidentally matches content inside a comment or CDATA block.

Using sed With External Script Files

When you’re running sed multiple commands, stuffing them all into one line gets ugly fast. Put them in a file instead.

Create a script file:

nano script.sed

Add your commands, one per line (no quotes needed):

s/old_pattern1/new_pattern1/g
/old_pattern2/d

Run it:

sed -f script.sed target_file.txt

Cleaner, version-controllable, and less likely to trip you up with quoting issues. For any operation beyond two or three commands, use a script file.

Script files also make your sed operations repeatable. Stick them in your project’s repo, add a comment at the top explaining what they do, and you’ve got a documented text transformation that anyone on the team can run. Beats a one-liner in your bash history that nobody can reconstruct three months later.

sed Backreferences in Regex

A sed backreference lets you capture part of a match and reuse it in the replacement. The captured portion is called a sed capture group, wrapped in escaped parentheses.

Classic example: reorder “Last, First” to “First Last”:

echo "Doe, John" | sed 's/\(.*\), \(.*\)/\2 \1/'

Output: John Doe

\1 refers to the first capture group (“Doe”), \2 to the second (“John”). A sed regular expression with backreferences can handle reformatting dates, reordering CSV columns, or extracting substrings from structured text. It’s one of the features that pushes sed from “handy” into “genuinely powerful.”

You can use up to nine capture groups in a single sed expression. In practice, if you’re going beyond three or four, you’re probably better off with Perl or Python. But for two-group operations like swapping fields, reversing name formats, or restructuring simple records, sed backreferences are fast to write and fast to run.

Linux sed Command FAQ

What is the sed command in Linux?

The sed command in Linux is a stream editor that filters and transforms text from the command line. It reads input line by line, applies your editing rules, and sends the result to standard output. You don’t need to open a file in an editor to change it. It’s been part of Unix since the 1970s and it’s still one of the fastest ways to manipulate text on any Linux system. Sed supports regular expressions, works with piped input, and handles files of any size because it processes them one line at a time rather than loading everything into memory.

How is sed different from grep?

Both are text processing tools, but they do different jobs. Grep searches files for matching patterns and prints those lines. That’s it. Sed can search and modify: substitute text, delete lines, insert content, reorder strings. Think of grep as a flashlight (finds things) and sed vs grep as a Swiss army knife (finds and fixes things).

How is sed used in a bash script?

Inside bash scripts, sed typically serves three roles: printing specific lines to stdout, deleting unwanted text, and replacing strings. You can assign sed output to variables, pipe it to other commands, or use it to modify config files during automated deployments. The syntax stays identical to what you’d type interactively. A common pattern is using shell variables inside sed commands with double quotes: sed "s/$OLD/$NEW/g" file.txt. Single quotes prevent variable expansion, so switch to double quotes when your patterns come from variables.

How is sed different from awk?

Sed handles straightforward text substitution, deletion, and insertion. Awk is a full programming language designed for column-based data processing. It supports variables, conditionals, loops, and arithmetic. The quick rule: if you’re replacing a string, use sed. If you’re summing a column of numbers or doing anything that feels like a spreadsheet operation, reach for awk. Sed vs awk comes down to simplicity versus power.

How to remove blank lines with sed?

Use the d command with a pattern that matches empty lines:

sed '/^$/d' myfilename.txt

The regex ^$ matches lines with nothing between start and end. This is one of the most common sed remove blank lines one-liners you’ll use. Add -i to edit the file directly.

Scroll to Top