GNU sed โ a stream editor, version 4.8. This document is the GNU sed manual.
| Use Case | Command | Description |
|---|---|---|
| Basic substitution | sed 's/old/new/' file | โ Replace first occurrence of 'old' with 'new' on each line |
| Global substitution | sed 's/old/new/g' file | ๐ Replace all occurrences |
| In-place edit | sed -i 's/old/new/' file | โ๏ธ Edit file directly (creates backup with -i.bak) |
| Print specific line | sed -n '45p' file | ๐ Print only line 45 |
| Delete lines | sed '3d' file | ๐๏ธ Delete line 3 |
| Delete range | sed '30,35d' file | ๐๏ธ Delete lines 30-35 |
| Case-insensitive match | sed '/pattern/Id' file | ๐ Delete lines matching 'pattern' case-insensitively |
| Extended regex | sed -E 's/[0-9]+/N/g' file | ๐ง Use extended regular expressions (fewer backslashes) |
| Print line numbers | sed -n '=' file | ๐ข Print line numbers only |
| Quit after match | sed '/pattern/q' file | ๐ช Print lines until pattern, then exit |
| Read file into stream | sed '2r /path/to/file' input | ๐ Insert file content after line 2 |
| Write matched lines to file | sed -n '/pattern/w output' input | ๐พ Write lines matching pattern to output file |
| Multiple commands | sed -e 's/foo/bar/' -e 's/baz/qux/' file | ๐ Chain multiple operations |
| Use sed script file | sed -f script.sed input | ๐ Execute commands from a file |
sed is a stream editor. It performs basic text transformations on an input stream (file or pipeline). Unlike editors like ed, sed makes only one pass over the input, making it efficient. Its ability to filter text in a pipeline distinguishes it from other editors.
This chapter covers how to run sed.
Normally invoked as:
sed SCRIPT INPUTFILE...
Example: replace all 'hello' with 'world' in input.txt:
sed 's/hello/world/' input.txt > output.txt
If no input file specified or - is given, reads from stdin. Use -i for in-place editing. Use -n to suppress automatic printing; use p to print specific lines. Multiple input files are treated as one long stream (use -s to treat separately).
Full format: sed OPTIONS... [SCRIPT] [INPUTFILE...]
--version โ ๐ Print version and copyright.--help โ โ Print usage summary.-n, --quiet, --silent โ ๐ Disable automatic printing (only explicit p commands output).--debug โ ๐ Print canonical sed program and annotate execution.-e SCRIPT, --expression=SCRIPT โ โ Add commands to the script.-f SCRIPT-FILE, --file=SCRIPT-FILE โ ๐ Add commands from file.-i[SUFFIX], --in-place[=SUFFIX] โ โ๏ธ Edit files in-place (creates backup with suffix).-l N, --line-length=N โ ๐ Set line-wrap length for l command (default 70).--posix โ ๐๏ธ Disable GNU extensions, make behavior POSIX-compliant.-b, --binary โ ๐พ Open files in binary mode (no CR-LF conversion).--follow-symlinks โ ๐ Follow symbolic links when using -i.-E, -r, --regexp-extended โ ๐ง Use extended regular expressions.-s, --separate โ ๐งฉ Treat input files as separate entities.--sandbox โ ๐๏ธ Reject e/w/r commands (safe mode).-u, --unbuffered โ โก Minimize buffering (useful for tail -f).-z, --null-data, --zero-terminated โ ๐งต Treat input as NUL-terminated lines.Exit codes: 0 = success, 1 = invalid command/syntax/regex, 2 = input file open failure, 4 = I/O or runtime error. The q and Q commands can return custom exit codes.
A sed program consists of one or more commands, passed via -e, -f, or first non-option argument. Command syntax: [addr]X[options]. Commands can be separated by ; or newlines. Some commands (a, c, i) cannot be followed by semicolons.
a\TEXT โ โ Append text after a line.b LABEL โ ๐ Branch unconditionally to label.c\TEXT โ ๐ Replace (change) lines with text.d โ ๐๏ธ Delete pattern space, start next cycle.D โ ๐๏ธ Delete up to first newline in pattern space.e โ ๐ Execute command in pattern space, replace with output.e COMMAND โ ๐ Execute COMMAND and send output to stdout.F โ ๐ Print current input file name.g โ โป๏ธ Replace pattern space with hold space.G โ โป๏ธ Append hold space to pattern space.h โ โป๏ธ Replace hold space with pattern space.H โ โป๏ธ Append pattern space to hold space.i\TEXT โ ๐ Insert text before a line.l โ ๐ Print pattern space unambiguously (C-style escapes).n โ โญ๏ธ Print pattern space (if auto-print enabled), then read next line.N โ โญ๏ธ Append next line to pattern space (with newline).p โ ๐จ๏ธ Print pattern space.P โ ๐จ๏ธ Print pattern space up to first newline.q[EXIT-CODE] โ ๐ช Quit (print pattern space, exit).Q[EXIT-CODE] โ ๐ช Quit silently (do not print pattern space).r filename โ ๐ Read file contents into output.R filename โ ๐ Queue a line from file to be read.s/REGEXP/REPLACEMENT/[FLAGS] โ ๐ Substitute matched text.t LABEL โ ๐ Branch if a successful substitution occurred.T LABEL โ ๐ Branch if no successful substitution.v [VERSION] โ โ
Verify GNU sed version (fails if not supported).w filename โ ๐พ Write pattern space to file.W filename โ ๐พ Write first line of pattern space to file.x โ ๐ Exchange hold and pattern spaces.y/src/dst/ โ ๐ Transliterate characters.z โ ๐งน Empty pattern space (zap).# โ ๐ฌ Comment (to end of line).{ CMD ; CMD ... } โ ๐ฆ Group commands.= โ ๐ข Print current line number.: LABEL โ ๐ท๏ธ Define label for branching.Syntax: s/REGEXP/REPLACEMENT/FLAGS. Replaces matched portion with REPLACEMENT. Supports backreferences \1โ\9, & for whole match. Case conversion: \L, \l, \U, \u, \E. Flags: g (global), NUMBER (replace Nth match), p (print), w FILENAME (write), e (execute result as command), I (case-insensitive), M (multi-line mode).
# โ ๐ฌ Comment (no addresses allowed). Warning: #n at start forces -n.q [EXIT-CODE] โ ๐ช Quit after printing current line.d โ ๐๏ธ Delete current line.p โ ๐จ๏ธ Print line (usually with -n).n โ โญ๏ธ Skip to next line.{ COMMANDS } โ ๐ฆ Group commands for a single address.y/SOURCE/DEST/ โ ๐ Transliterate characters.a TEXT โ โ Append text after a line (GNU extension).a\TEXT โ โ Append text with line continuation.i TEXT โ ๐ Insert text before a line.i\TEXT โ ๐ Insert with line continuation.c TEXT โ ๐ Replace line(s) with text.c\TEXT โ ๐ Replace with line continuation.= โ ๐ข Print line number.l N โ ๐ Unambiguous print (with line-wrap length).r FILENAME โ ๐ Read file contents.w FILENAME โ ๐พ Write pattern space to file.D โ ๐๏ธ Delete first line of pattern space.N โ โญ๏ธ Append next line to pattern space.P โ ๐จ๏ธ Print first line of pattern space.h, H, g, G, x โ โป๏ธ Hold space operations.: LABEL โ ๐ท๏ธ Define label.b LABEL โ ๐ Unconditional branch.t LABEL โ ๐ Conditional branch (if substitution succeeded).e [COMMAND] โ ๐ Execute command; output replaces pattern space or goes to stdout.F โ ๐ Print filename.Q [EXIT-CODE] โ ๐ช Quit silently.R FILENAME โ ๐ Queue a line from file.T LABEL โ ๐ Branch if substitution failed.v VERSION โ โ
Verify GNU sed version.W FILENAME โ ๐พ Write first line of pattern space.z โ ๐งน Empty pattern space.Commands can be separated by newlines, -e options, or semicolons (for most commands). Commands a, c, i, #, r, R, w, W, e, and s///[we] require newlines to terminate text/filenames.
Addresses determine which lines commands apply to. They can be a line number, a regular expression, or a range. Negation with !.
NUMBER โ Match specific line.$ โ Last line.FIRST~STEP โ GNU extension: match every STEPth line starting from FIRST./REGEXP/ โ Match lines containing REGEXP.\%REGEXP% โ Use alternative delimiter./REGEXP/I โ Case-insensitive match./REGEXP/M โ Multi-line mode (^ and $ match line boundaries).Two addresses separated by comma. Special forms: 0,/REGEXP/ (includes first line), ADDR1,+N (N lines after), ADDR1,~N (up to next multiple of N).
Regular expressions are patterns matched against subject strings. Most characters are ordinary; special characters include ^, $, ., *, etc.
Basic (default) vs Extended (-E). In BRE, +, ?, {}, (), | need backslash to be special. In ERE, they are special without backslash.
CHAR โ Literal character.* โ Zero or more of preceding.. โ Any character (including newline).^ โ Start of line.$ โ End of line.[LIST] โ Character class.\+ โ One or more (GNU extension).\? โ Zero or one (GNU extension).\{I\} โ Exactly I times.\(REGEXP\) โ Grouping.REGEXP1\|REGEXP2 โ Alternation.\DIGIT โ Backreference.\n โ Newline.Same as BRE but with opposite escaping: +, ?, {}, (), | are special without backslash.
Bracket expressions [...] match one character. Named classes: [:alnum:], [:alpha:], [:blank:], [:cntrl:], [:digit:], [:graph:], [:lower:], [:print:], [:punct:], [:space:], [:upper:], [:xdigit:].
\w โ Word character (letter, digit, underscore).\W โ Non-word character.\b โ Word boundary.\B โ Non-word boundary.\s โ Whitespace (space, tab, newline).\S โ Non-whitespace.\< โ Beginning of word.\> โ End of word.\` โ Start of pattern space.\' โ End of pattern space.Back-references \1โ\9 refer to parenthesized subexpressions. Used in both patterns and replacement.
Non-printable characters: \a (BEL), \f (form feed), \n (newline), \r (CR), \t (tab), \v (vertical tab), \cX (control), \dXXX (decimal), \oXXX (octal), \xXX (hex).
GNU sed handles UTF-8 multibyte characters. Invalid sequences are not matched by .. Use z command to clear pattern space. Upper/lower conversion works with multibyte. Use LC_ALL=C for bytewise processing.
Two buffers: pattern space (active) and hold space (auxiliary). For each line: read, execute commands, print (unless -n), then next cycle.
Use h, H, g, G, x to move data between buffers.
Use N, D, P, G, H to process multiple lines. Example: process paragraphs with sed '/./{H;$!d} ; x ; s/REGEXP/REPLACEMENT/'.
Commands b (unconditional), t (conditional on success), T (conditional on failure) change flow. Labels defined with :LABEL. Branching can create loops, join lines, etc.
Join specific lines: sed '2{N;s/\n//;}'. Join backslash-continued lines: sed -e ':x /\\$/ { N; s/\\\n//g ; bx }'. Join lines starting with whitespace: sed -E ':a ; $!N ; s/\n\s+/ / ; ta ; P ; D'.
Center text to 80 columns using hold space and pattern manipulations.
Replace trailing 9s with underscores, increment last digit, then replace underscores with zeros.
Generate shell commands to rename files using sed and y command.
Strip function definitions from set output.
Using markers and loops to reverse character order.
Find doubled words using N and D with backreferences.
Wrap lines at 40 characters using nested loops.
Accumulate lines in hold space and print at end.
Complex script using hold space and y for incrementing numbers.
Similar but skip blank lines.
Map characters to letters, propagate carries, convert back to decimal.
Convert words to 'a's, then count like characters.
Just $=.
10q.
Sliding window technique using N and D.
Using N, P, D to compare adjacent lines.
Print only lines that appear more than once.
Print only unique lines.
Various scripts to reduce multiple blank lines to one.
GNU sed has no built-in line length limit (only memory). Recursion may limit stack for complex patterns.
Email to bug-sed@gnu.org with sed --version output. Provide a minimal test case. Known non-bugs include: N on last line, regex backslash semantics, -i on read-only files, 0a not working, [a-z] locale sensitivity, s/.*// not clearing multibyte patterns.
Generated by phpman v4.9.26-1-g511901d · Markdown · JSON · MCP Author: Che Dong Under GNU General Public License
2026-08-02 06:25 @216.73.217.9
CrawledBy Mozilla/5.0 AppleWebKit/537.36 (KHTML, like Gecko; compatible; ClaudeBot/1.0; +claudebot@anthropic.com)
Enhanced by LLM: deepseek-v4-flash / taotoken.net / www.chedong.com - original format