Invoking sed 20
Exit status: 0 on success, 1 for an invalid command, syntax or regular expression, 2 when an input file could not be opened, 4 for an I/O or runtime error; q and Q can set their own code.
| Command | What it does |
|---|---|
sed SCRIPT INPUTFILE... | Run a script on input filesWith no INPUTFILE, or with - in its place, sed filters standard input; the result goes to standard output. |
-n | Turn off automatic printingLong forms --quiet and --silent; output then appears only where the script asks for it, for example with p. |
-e SCRIPT | Pass a script inlineLong form --expression=SCRIPT; repeat it to give several scripts, which are joined in the order given. |
-f SCRIPT-FILE | Read the script from a fileLong form --file=SCRIPT-FILE; it can be mixed with -e, and all the pieces are concatenated into one script. |
-E | Use extended regular expressionsAlso accepted as -r or --regexp-extended; -E is the spelling that entered POSIX, so prefer it in portable scripts. |
-i[SUFFIX] | Edit files in placeLong form --in-place[=SUFFIX]; with a suffix the original is kept as a backup under the extended name, without one it is overwritten. |
sed -iE '...' FILE | Backup suffix pitfall with -iEWhatever follows -i is taken as the suffix, so this means --in-place=E and leaves a backup named FILEE. |
sed -ni 's/foo/bar/' FILE | Pitfall: -ni truncates the fileWith automatic printing off and no p command, nothing is written back and FILE ends up empty. |
--follow-symlinks | Edit the target of a symlinkOnly has an effect together with -i; by default the link itself is replaced and its destination stays untouched. |
-s | Treat each file separatelyLong form --separate; line numbers restart and $ means the last line of every file; -i implies it. |
-z | Split input on NUL bytesLong forms --null-data and --zero-terminated; pairs with sort -z or find -print0 to handle arbitrary file names. |
-u | Use minimal bufferingLong form --unbuffered; helps when the input comes from something like tail -f and results should appear immediately. |
-l N | Set line-wrap length for lLong form --line-length=N; 0 turns wrapping off, and 70 is used when the option is absent. |
-b | Open input in binary modeLong form --binary; matters only on MS-DOS, Windows and Cygwin, where text mode would hide the carriage return from sed. |
--posix | Disable GNU extensionsSwitches off every extension the manual describes, extra commands included, to make portable scripts simpler to write. |
--sandbox | Reject e, w and r commandsA script that contains any of them is aborted before it runs, so sed touches only the named input files. |
--debug | Trace how the script runsPrints the script in canonical form, then the pattern space and each command as it is executed. |
--help | Show a usage summaryPrints a short reminder of the options plus where to report bugs, then exits. |
--version | Show the sed versionPrints which sed is running together with its copyright notice, then exits. |
info sed | Open the full manualThe man page is only a brief synopsis; this opens the Texinfo manual when info and sed are installed. |
Substitution 12
Any single character can stand in for the three slashes of an s command; that character then needs a backslash wherever it occurs inside the pattern or the replacement.
| Command | What it does |
|---|---|
s/REGEXP/REPLACEMENT/FLAGS | Substitute matched textReplaces the part of the pattern space that REGEXP matches; with no flags only the first match on a line changes. |
sed 's/hello/world/' input.txt > output.txt | Replace first match per lineEvery line is processed, but only its first hello becomes world; the result is written to output.txt. |
sed 's/hello/world/g' input.txt > output.txt | Replace every match in a fileThe g flag changes all occurrences of hello in input.txt, not just the first one on each line. |
| & | Insert the whole matchStands for everything REGEXP matched; put a backslash before it to get a literal ampersand. |
\N | Insert a captured groupN is a digit from 1 to 9 and stands for the text matched by the Nth \( ... \) pair. |
\L | Lowercase the replacementGNU extension; applies to the rest of the replacement until \U or \E appears. |
\l | Lowercase the next characterGNU extension; changes only the single character that follows it in the replacement. |
\U | Uppercase the replacementGNU extension; stays in force for the remaining replacement text until \L or \E appears. |
\u | Uppercase the next characterGNU extension; capitalises just one character, for example the first letter of a captured group. |
\E | End case conversionStops a conversion that \L or \U started, so the text after it keeps its own case. |
sed 's/.*/\L&/' | Convert a line to lowercaseMatches the whole line and writes it back in lower case; multibyte characters are converted too. |
sed -E 's/(.*) (.*)/The name is \2, \1 \2./' | Reorder two captured wordsWith -E the groups need no backslashes; \2 and \1 place the second word ahead of the first. |
Substitution flags 7
| Command | What it does |
|---|---|
| g | Replace all matches on a lineWithout this flag only the first match of REGEXP in each line is replaced. |
NUMBER | Replace only the Nth matchCombined with g, GNU sed skips the earlier matches and replaces that one and all later ones. |
| p | Print the line when changedOutputs the new pattern space, but only if a replacement was actually made on that line. |
w FILENAME | Write changed lines to a fileOnly lines where a replacement happened are written; /dev/stdout and /dev/stderr are accepted as GNU extensions. |
| e | Execute the result in a shellAfter a replacement the pattern space is run as a command and replaced by its output; GNU extension. |
| I | Ignore case when matchingGNU extension; on the s command a lowercase i means the same thing. |
| M | Match in multi-line modeLets ^ and $ also match right after and right before each newline in the pattern space; GNU extension, also written m. |
Addresses and ranges 18
| Command | What it does |
|---|---|
[addr]X[options] | General command syntaxX is a one-letter command; the optional address limits it to matching lines, and some commands take options. |
NUMBER | Match one line by numberCounting continues from one input file into the next, except with -i or -s. |
| $ | Match the last lineMeans the final line of the whole input, or of every file once -i or -s is in effect. |
FIRST~STEP | Match lines at a fixed intervalGNU extension: 1~2 picks the odd-numbered lines, 0~2 the even ones and 2~3 every third line from line 2. |
sed -n 1~2p | Print odd-numbered linesA step address that starts at line 1 and advances two lines at a time. |
/REGEXP/ | Match lines by regular expressionA slash inside the expression needs a backslash; an empty // reuses the expression matched last. |
sed -n '/bash$/p' /etc/passwd | Print lines ending with a stringShows the /etc/passwd lines that finish with bash, much as grep would. |
\%REGEXP% | Match with a custom delimiterAny single character can take the place of %, which saves escaping each slash in a path. |
/REGEXP/I | Match an address ignoring caseGNU extension; it must be a capital I, because a lowercase i after an address is the insert command. |
sed '144s/hello/world/' input.txt > output.txt | Substitute on one line onlyThe number in front of s restricts the replacement to line 144. |
sed '/apple/s/hello/world/' input.txt > output.txt | Substitute on matching linesThe replacement runs only where the line contains apple. |
sed '4,17s/hello/world/' input.txt > output.txt | Substitute within a line rangeTwo addresses joined by a comma form an inclusive range, here lines 4 through 17. |
| ! | Negate an addressWritten after the address or range and ahead of the command; the command then runs on the lines not selected. |
sed '/apple/!s/hello/world/' input.txt > output.txt | Substitute on non-matching linesThe ! inverts the address, so lines without apple are the ones edited. |
sed -n '4,6p' | Print a range of linesBoth ends belong to the range, so the output is lines 4, 5 and 6. |
0,/REGEXP/ | Range that may end on line 1GNU extension: unlike 1,/REGEXP/, a match on the first input line already closes the range. |
ADDR1,+N | Match a line and N moreGNU extension; the start can be given as a number or as a regex. |
ADDR1,~N | Match up to a multiple of NGNU extension; the range runs from ADDR1 to the nearest following line whose number divides evenly by N. |
Deleting, printing and quitting 16
| Command | What it does |
|---|---|
| d | Delete the current lineDiscards the pattern space and begins a new cycle at once, so nothing is printed for that line. |
sed 2d | Delete the second lineA bare number is the address, so only line 2 is missing from the output. |
sed '30,35d' input.txt > output.txt | Delete a range of linesRemoves lines 30 through 35 and writes everything else to output.txt. |
/^#/d | Delete lines starting with #Reads as an if-then: when the line begins with a hash, d removes it without printing. |
| D | Delete first line of pattern spaceRestarts the cycle on what is left without reading input; when no newline is present it acts like d. |
| p | Print the pattern spaceNormally combined with the -n option, which turns off the automatic output of every line. |
sed -n 2p | Print only the second lineAutomatic printing is off, so the p command is the single source of output. |
sed -n '/hello/p' | Print lines containing a stringThe sed counterpart of running grep with the same word. |
| P | Print first line of pattern spaceOutputs only the text before the first newline; useful once N has joined several lines. |
l N | Show the line in escaped formNon-printable characters appear as C-style escapes and each line ends with $; the optional N sets the wrap length (GNU extension). |
| = | Print the line numberThe number is written on a line of its own ahead of the text. |
| n | Move on to the next linePrints the pattern space unless -n is set, then loads the following input line; handy for acting on every Nth line. |
q [EXIT-CODE] | Quit after the current linePrints the pattern space unless -n is set and takes one address only; the exit code is a GNU extension. |
sed 2q | Stop after the second lineLines 1 and 2 are printed, then sed exits and the remaining input is left alone. |
sed '/^foo/q42' input.txt > output.txt | Quit with an exit statusCopies input until a line begins with foo, then stops with status 42; if none does, the status is 0. |
Q [EXIT-CODE] | Quit without printingSame as q except that the current pattern space is not output; GNU extension, one address only. |
Inserting and changing text 12
a, i and c take the rest of the line as their text, so a semicolon after them does not start a new command: end them with a newline or put the next command in its own -e.
| Command | What it does |
|---|---|
a TEXT | Add a line after the matchOne-line GNU form; whitespace in front of TEXT is dropped and the text runs to the end of the line. |
sed '2a hello' | Add a line after line 2The new line hello appears between the original lines 2 and 3. |
a\ | Append text, portable formPOSIX syntax: the text starts on the following script line, and every line of it but the last ends with a backslash. |
sed -e '2a\' -e "$VAR" | Append text from a shell variableGNU sed lets the a command and its text sit in two separate -e arguments, which keeps the quoting simple. |
i TEXT | Insert a line before the matchOne-line GNU form of the insert command; the text is printed ahead of the addressed line. |
i\ | Insert text, portable formPOSIX syntax with the text on the following script lines; it is written out at once. |
sed -i '1i/* Copyright (C) FOO BAR */' *.c | Add a header line to filesEdits every .c file in place and inserts the comment above its first line. |
c TEXT | Replace lines with textOne-line GNU form; with an address range the whole range is replaced by a single copy of TEXT. |
sed '2,9c hello' | Replace a range with one lineLines 2 to 9 disappear and a single hello takes their place. |
c\ | Change lines, portable formDeletes the addressed lines and prints the text given on the next script lines; a new cycle then starts. |
y/SOURCE-CHARS/DEST-CHARS/ | Transliterate charactersMaps each character of the first list to the one at the same position in the second; both lists need equal length. |
sed 'y/abcdefghij/0123456789/' | Transliterate letters to digitsEach letter from a to j is swapped for the digit in the same position, much as tr would do. |
Hold space and multi-line editing 9
| Command | What it does |
|---|---|
| h | Copy pattern space to hold spaceOverwrites whatever the hold space contained before. |
| H | Append pattern space to hold spaceA newline is added to the hold space first, so saved lines pile up there one per line. |
| g | Copy hold space to pattern spaceThe current line is discarded and replaced by what was saved earlier. |
| G | Append hold space to pattern spaceAdds a newline and then the saved text after the current line. |
| x | Swap hold and pattern spacesWhat was saved becomes the line being edited, and the line being edited is saved in its place. |
| N | Append the next input lineJoins the following line onto the pattern space with a newline between them, so one regex can span both. |
| z | Empty the pattern spaceUsually equals s/.*// but is faster and also copes with invalid multibyte input; GNU extension. |
sed -n 'N;l;D' | Show a sliding two-line windowN adds the next line, l displays the pair with escapes, and D drops the first line before the next cycle. |
sed '/./{H;$!d} ; x ; s/REGEXP/REPLACEMENT/' | Edit text paragraph by paragraphNon-empty lines collect in the hold space; at each blank line x brings the paragraph back for the s command. |
Files and multiple scripts 16
r, R, w and W read the file name up to the end of the line, spaces and semicolons included, and sed says nothing when such a file cannot be read or written.
| Command | What it does |
|---|---|
sed -i 's/hello/world/' file.txt | Change a file in placeRewrites file.txt itself and sends nothing to standard output. |
sed -n '1p ; $p' one.txt two.txt three.txt | Print first and last input lineSeveral files form one stream, so this gives line 1 of one.txt and the final line of three.txt; -s changes that. |
sed '/^foo/d ; s/hello/world/g' input.txt > output.txt | Chain commands with a semicolonBoth commands sit in one script and are applied to every line in that order. |
sed -e '/^foo/d' -e 's/hello/world/g' input.txt > output.txt | Run two scripts with -eDeletes lines that start with foo and swaps hello for world in the rest; equal to one script joined by a semicolon. |
sed -f script.sed input.txt > output.txt | Run a script filescript.sed holds one command per line, here written beforehand with two echo commands. |
sed '1d;3d;5d' | Separate commands with semicolonsWorks for most simple commands; a, i, c, r, w and e take the rest of the line and need a newline instead. |
{ COMMANDS } | Group commands under one addressEverything between the braces runs only when the address or range in front of them matches. |
sed -n '2{s/2/X/ ; p}' | Substitute then print one lineBoth commands inside the braces apply to line 2 only. |
| # | Start a commentRuns to the next newline; a script whose first two characters are #n behaves as if -n were given. |
r FILENAME | Insert a file after a lineThe contents are queued and printed when the cycle ends; an unreadable file counts as empty and raises no error. |
sed -i '0rLIC.TXT' *.cpp *.h | Prepend a file to many filesAddress 0 with r puts LIC.TXT above the first line of each file; needs GNU sed 4.9 or later. |
R FILENAME | Insert one line from a fileEach run takes one more line from the file and queues it for output; GNU extension. |
w FILENAME | Write lines to a fileWrites the whole pattern space; /dev/stdout and /dev/stderr are special names in GNU sed. |
W FILENAME | Save first line of pattern spaceWrites only the text before the first newline; file handling follows the w command; GNU extension. |
| F | Print the current file nameOutputs the name of the input file being read, on a line of its own; GNU extension. |
e COMMAND | Run a shell commandThe output is printed at once; with no argument the pattern space itself is executed and replaced by the result. |
Branching and labels 6
| Command | What it does |
|---|---|
: LABEL | Define a labelA target for b, t and T; takes no address and does nothing else. |
b LABEL | Branch to a labelAlways jumps; when the label is left out, the rest of the script is skipped and a new cycle begins. |
t LABEL | Branch if a substitution succeededJumps only when an s command has replaced something after the latest line was read or the latest t or T. |
T LABEL | Branch if no substitution succeededThe opposite test of t; GNU extension. |
sed '/1/b x ; s/^/=/ ; :x ; 3d' | Skip commands for matching linesLines containing 1 jump to label x and miss the substitution; GNU sed reads the label up to the semicolon. |
sed ':x ; $!N ; s/=\n// ; tx ; P ; D' jaques.txt | Rejoin soft-wrapped linesN appends a line, s removes one soft break, t repeats while that succeeds, then P and D emit the first line. |
Regular expression syntax 14
| Command | What it does |
|---|---|
| * | Zero or more repetitionsApplies to the preceding character, bracket expression or group; a*b matches b as well as aaaaab. |
| . | Any single characterAlso matches a newline inside the pattern space. |
| ^ | Start of the pattern spaceSpecial only at the beginning of an expression or group; normally that means the start of the line. |
| $ | End of the pattern spaceSpecial only as the last character of an expression or group. |
[LIST] | Any one listed characterFor instance [aeiou] finds any vowel; written [^LIST] it matches any character not in the list. |
\+ | One or more repetitionsGNU extension in basic syntax; with -E write a plain + instead. |
\? | Zero or one occurrenceGNU extension in basic syntax; under -E the question mark needs no backslash. |
\{I,J\} | Between I and J repetitionsAlso \{I\} for exactly I and \{I,\} for I or more; with -E drop the backslashes. |
\(REGEXP\) | Group an expressionLets a repetition operator apply to the whole group and makes the match available to back-references. |
REGEXP1\|REGEXP2 | Match either alternativeGNU sed tries them in order and takes the first one that matches; with -E write a plain |
\n | Match a newlineUseful after N, G or H have put several lines into the pattern space. |
\w | Any word characterA letter, a digit or the underscore; \W is the opposite. |
\b | Word boundaryMatches the empty position between a word character and a non-word character; \B matches everywhere else. |
sed 's/[[:digit:]]/X/' | Use a named character classClass names such as [:digit:] only work inside an outer pair of brackets. |
Examples from the manual 7
| Command | What it does |
|---|---|
sed '2{N;s/\n//;}' lines.txt | Join two specific linesOn line 2, N pulls in line 3 and the substitution removes the newline between them. |
sed -e ':x /\\$/ { N; s/\\\n//g ; bx }' 1.txt | Join lines ending in a backslashWhile a line ends with a backslash, N adds the next one and the backslash-newline pair is removed; needs GNU sed. |
sed -E ':a ; $!N ; s/\n\s+/ / ; ta ; P ; D' 2.txt | Join indented continuation linesA line that begins with whitespace is folded onto the one before it, as with wrapped mail headers. |
sed -En '/\b(\w+)\s+\1\b/p' two-cities-dup1.txt | Find doubled words on a linePrints lines where a word is immediately followed by the same word, such as the the. |
sed -En '{N; /\b(\w+)\s+\1\b/{=;p} ; D}' two-cities-dup2.txt | Find doubled words across linesN and D keep two lines in the pattern space, so a repeat split over a line break is found too. |
10q | Print the first 10 linesA whole script for sed -f that works like head; change the number in front of q for another count. |
$= | Count linesRun as a script with -n, it prints only the number of the last line, like wc -l. |
No row on this page matches that filter.
Notes
The substitution and its flags
s/REGEXP/REPLACEMENT/FLAGS replaces the first match on each line; the g flag replaces every match, I ignores case, and a number replaces only that occurrence. Any delimiter works — s|/usr/local|/opt| avoids escaping slashes in paths. In the replacement, & stands for the whole match. -E switches to extended regular expressions so groups are (...) rather than \(...\), and \1 in the replacement refers back to a group. -n suppresses the default print so only lines you explicitly print with a p flag appear, which turns sed into a grep with capture groups: sed -nE 's/^user=(.*)/\1/p'.
Editing files in place
-i[SUFFIX] edits the file rather than printing; -i.bak keeps a backup and plain -i does not. The option takes its suffix from whatever follows it directly, so it must come last in a cluster of short options: sed -iE '...' FILE makes a backup called FILEE instead of turning on extended syntax, and sed -ni 's/foo/bar/' FILE without a p leaves the file empty. The BSD sed on macOS is a different program whose -i always expects a suffix argument (-i '' for none); an attached suffix such as -i.bak is the spelling both accept. -i already implies -s, so addresses such as 1 or $ apply to each file. Use --sandbox when running scripts you did not write, since it rejects any script that contains the e, w or r commands.
Addresses and the rest of the script
A command can be limited to lines by address: /REGEXP/ for matching lines, a number for one line, 1,10 for a range, FIRST~STEP for every n-th line and ADDR1,+N for a line and the N after it; ! after the address inverts it. Deleting matching lines is /pattern/d; printing a range is -n '10,20p'. y/SOURCE-CHARS/DEST-CHARS/ transliterates characters, q [EXIT-CODE] stops after the current line — the one-line script 10q is a fast head — and -e SCRIPT or -f SCRIPT-FILE chain several commands. The branching commands b LABEL and t LABEL exist for multi-line scripts, though the manual itself says that needing them usually means awk or Perl would serve better.
Questions
How do I replace all occurrences on a line?
Add the g flag: sed 's/old/new/g'. Without it only the first match per line changes.
How do I edit a file in place safely?
sed -i.bak 's/old/new/' file keeps a backup as file.bak. With GNU sed a plain -i makes no backup; the BSD sed on macOS needs -i '' for that.
How do I print only the lines that match?
Use -n with the p command: sed -n '/pattern/p' file, or -nE with a capture group and the p flag of s to print just part of the line.
How do I delete lines matching a pattern?
sed '/pattern/d' file. Add -i to change the file itself.
Which sed does this page describe?
GNU sed, the version found on Linux. The rows come from the GNU sed 4.9 manual and the sed(1) page of 4.10. Anything marked GNU extension may be missing or behave differently in other implementations such as the BSD sed on macOS; --posix switches those extensions off.
Sources and checks
- GNU sed manual for version 4.9 (Free Software Foundation), Info edition shipped with sed 4.9 Command-line options, the s command and its flags, addresses, every script command, regular-expression syntax and the sample scripts
- sed(1) manual page of GNU sed 4.10 (Linux man-pages online, man7.org) Option summary of the newer 4.10 release, the 1~2p step-address example and the pointer to the Info manual
Every row on this page was matched to a line in the documentation above on . A binding that could not be found there is not listed.
Found a wrong or missing key? Tell us and it gets checked against the source. How we verify describes the process and its limits.