sed commands

GNU sed options, script commands, address forms and one-liners from the GNU sed 4.9 manual, checked against the sed(1) page of release 4.10 and grouped by task. Options appear without the leading sed; rows that begin with sed are command lines printed in the manual. Most everyday use is s/REGEXP/REPLACEMENT/FLAGS with -n, -E or -i[SUFFIX] in front. Rows marked GNU extension may not work in the BSD sed on macOS; the long multi-line sample scripts are left out.

137 commands in 11 sections. Checked row by row against GNU sed manual for version 4.9 (Free Software Foundation), Info edition shipped with sed 4.9 on . Edited by Jay.

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.

CommandWhat 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.
-nTurn off automatic printingLong forms --quiet and --silent; output then appears only where the script asks for it, for example with p.
-e SCRIPTPass a script inlineLong form --expression=SCRIPT; repeat it to give several scripts, which are joined in the order given.
-f SCRIPT-FILERead the script from a fileLong form --file=SCRIPT-FILE; it can be mixed with -e, and all the pieces are concatenated into one script.
-EUse 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 '...' FILEBackup 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/' FILEPitfall: -ni truncates the fileWith automatic printing off and no p command, nothing is written back and FILE ends up empty.
--follow-symlinksEdit the target of a symlinkOnly has an effect together with -i; by default the link itself is replaced and its destination stays untouched.
-sTreat each file separatelyLong form --separate; line numbers restart and $ means the last line of every file; -i implies it.
-zSplit input on NUL bytesLong forms --null-data and --zero-terminated; pairs with sort -z or find -print0 to handle arbitrary file names.
-uUse minimal bufferingLong form --unbuffered; helps when the input comes from something like tail -f and results should appear immediately.
-l NSet line-wrap length for lLong form --line-length=N; 0 turns wrapping off, and 70 is used when the option is absent.
-bOpen input in binary modeLong form --binary; matters only on MS-DOS, Windows and Cygwin, where text mode would hide the carriage return from sed.
--posixDisable GNU extensionsSwitches off every extension the manual describes, extra commands included, to make portable scripts simpler to write.
--sandboxReject e, w and r commandsA script that contains any of them is aborted before it runs, so sed touches only the named input files.
--debugTrace how the script runsPrints the script in canonical form, then the pattern space and each command as it is executed.
--helpShow a usage summaryPrints a short reminder of the options plus where to report bugs, then exits.
--versionShow the sed versionPrints which sed is running together with its copyright notice, then exits.
info sedOpen 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.

CommandWhat it does
s/REGEXP/REPLACEMENT/FLAGSSubstitute 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.txtReplace 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.txtReplace 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.
\NInsert a captured groupN is a digit from 1 to 9 and stands for the text matched by the Nth \( ... \) pair.
\LLowercase the replacementGNU extension; applies to the rest of the replacement until \U or \E appears.
\lLowercase the next characterGNU extension; changes only the single character that follows it in the replacement.
\UUppercase the replacementGNU extension; stays in force for the remaining replacement text until \L or \E appears.
\uUppercase the next characterGNU extension; capitalises just one character, for example the first letter of a captured group.
\EEnd 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

CommandWhat it does
gReplace all matches on a lineWithout this flag only the first match of REGEXP in each line is replaced.
NUMBERReplace only the Nth matchCombined with g, GNU sed skips the earlier matches and replaces that one and all later ones.
pPrint the line when changedOutputs the new pattern space, but only if a replacement was actually made on that line.
w FILENAMEWrite changed lines to a fileOnly lines where a replacement happened are written; /dev/stdout and /dev/stderr are accepted as GNU extensions.
eExecute the result in a shellAfter a replacement the pattern space is run as a command and replaced by its output; GNU extension.
IIgnore case when matchingGNU extension; on the s command a lowercase i means the same thing.
MMatch 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

CommandWhat 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.
NUMBERMatch 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~STEPMatch 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~2pPrint 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/passwdPrint 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/IMatch 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.txtSubstitute on one line onlyThe number in front of s restricts the replacement to line 144.
sed '/apple/s/hello/world/' input.txt > output.txtSubstitute on matching linesThe replacement runs only where the line contains apple.
sed '4,17s/hello/world/' input.txt > output.txtSubstitute 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.txtSubstitute 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,+NMatch a line and N moreGNU extension; the start can be given as a number or as a regex.
ADDR1,~NMatch 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

CommandWhat it does
dDelete the current lineDiscards the pattern space and begins a new cycle at once, so nothing is printed for that line.
sed 2dDelete the second lineA bare number is the address, so only line 2 is missing from the output.
sed '30,35d' input.txt > output.txtDelete a range of linesRemoves lines 30 through 35 and writes everything else to output.txt.
/^#/dDelete lines starting with #Reads as an if-then: when the line begins with a hash, d removes it without printing.
DDelete first line of pattern spaceRestarts the cycle on what is left without reading input; when no newline is present it acts like d.
pPrint the pattern spaceNormally combined with the -n option, which turns off the automatic output of every line.
sed -n 2pPrint 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.
PPrint first line of pattern spaceOutputs only the text before the first newline; useful once N has joined several lines.
l NShow 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.
nMove 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 2qStop 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.txtQuit 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.

CommandWhat it does
a TEXTAdd 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 TEXTInsert 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 */' *.cAdd a header line to filesEdits every .c file in place and inserts the comment above its first line.
c TEXTReplace 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

CommandWhat it does
hCopy pattern space to hold spaceOverwrites whatever the hold space contained before.
HAppend pattern space to hold spaceA newline is added to the hold space first, so saved lines pile up there one per line.
gCopy hold space to pattern spaceThe current line is discarded and replaced by what was saved earlier.
GAppend hold space to pattern spaceAdds a newline and then the saved text after the current line.
xSwap hold and pattern spacesWhat was saved becomes the line being edited, and the line being edited is saved in its place.
NAppend the next input lineJoins the following line onto the pattern space with a newline between them, so one regex can span both.
zEmpty 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.

CommandWhat it does
sed -i 's/hello/world/' file.txtChange a file in placeRewrites file.txt itself and sends nothing to standard output.
sed -n '1p ; $p' one.txt two.txt three.txtPrint 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.txtChain 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.txtRun 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.txtRun 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 FILENAMEInsert 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 *.hPrepend 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 FILENAMEInsert one line from a fileEach run takes one more line from the file and queues it for output; GNU extension.
w FILENAMEWrite lines to a fileWrites the whole pattern space; /dev/stdout and /dev/stderr are special names in GNU sed.
W FILENAMESave first line of pattern spaceWrites only the text before the first newline; file handling follows the w command; GNU extension.
FPrint the current file nameOutputs the name of the input file being read, on a line of its own; GNU extension.
e COMMANDRun 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

CommandWhat it does
: LABELDefine a labelA target for b, t and T; takes no address and does nothing else.
b LABELBranch to a labelAlways jumps; when the label is left out, the rest of the script is skipped and a new cycle begins.
t LABELBranch 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 LABELBranch 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.txtRejoin 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

CommandWhat 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\|REGEXP2Match either alternativeGNU sed tries them in order and takes the first one that matches; with -E write a plain
\nMatch a newlineUseful after N, G or H have put several lines into the pattern space.
\wAny word characterA letter, a digit or the underscore; \W is the opposite.
\bWord 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

CommandWhat it does
sed '2{N;s/\n//;}' lines.txtJoin 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.txtJoin 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.txtJoin 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.txtFind 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.txtFind doubled words across linesN and D keep two lines in the pattern space, so a repeat split over a line break is found too.
10qPrint 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.

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

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.