A port to change in a configuration, comments to strip before handing a file to a program: sed does these jobs in one command, without opening an editor. It reads a text line by line, applies the commands you give it to each line, and writes the result to standard output. The original file only changes if you ask for it with -i.
The lesson Search and replace in a file has already shown s, -i and .bak. This page adds what it does not cover: the read cycle, addresses and their silent pitfalls, and editing a file with a way back.
What you will learn
- Predict what
sedprints and what becomes of the file, with or without-nand-i - Replace text with
sand check that the replacement happened - Choose the lines that are touched: number, pattern, range between two patterns, negation
- Reuse the matched text with
&and groups, and add a line - Edit a file with
-iwithout overwriting its backup, then roll back - Recognise the cases where
jq,yq,awkor Ansible are a better fit thansed
Prerequisites
You know how to use redirections and pipes, compare two files with diff (the 3c3 format, exit code 1 when they differ), and you have read Regular expression basics: the ^ and $ anchors, classes, basic and extended regular expressions (-E). The sed script is written between single quotes, so that the shell does not interpret $, * or \.
Create the practice folder
Type these commands as they are: they create four files and a symbolic link in ~/sed-lab. The commands of the lesson are run from this folder.
mkdir -p ~/sed-lab && cd ~/sed-labexport LC_ALL=C.UTF-8
printf '%s\n' '# configuration' 'host=serveur serveur' 'port=8080' '[db]' 'user=admin' 'port=5432' '[web]' 'port=80' 'date=2026-11-24' '[cache]' 'debug=false' > config.confprintf '%s\n' '# serveur' 'host=localhost' 'port=8080' > app.confprintf '%s\n' '/usr/local/bin/app' '/etc/app/app.conf' '/var/log/app.log' > paths.txtprintf 'port=8080\r\nhost=a\r\n' > dos.confln -s config.conf lien.confexport LC_ALL=C.UTF-8 makes sed print its messages in English, as shown here. In config.conf (eleven lines), host=serveur serveur is line 2, port=8080 is line 3, and [db], [web], [cache] open sections. app.conf is used by the anatomy and the map, dos.conf has Windows line endings and lien.conf points to config.conf. The file contents use French words, which the commands keep: serveur is "server" and lien is "link". The outputs come from GNU sed 4.9, tested on Debian 13, AlmaLinux 10 and Ubuntu 26.04. The sed of macOS or BSD differs: see "Pitfall: -i is not written the same way on macOS and BSD".
The sed command in detail
A sed command is always written in the same order: the options, then the script between single quotes, then the file. The script holds an address, which chooses the lines, and an action, which says what to do with them. In the example below, without /^port=/ every line is processed; without -n every line is printed.
Anatomy of the command
Syntaxsed [options] '[address]command' [file...]
sed-n/^port=/s80809090papp.conf -
sedthe programThe command run in the shell. It reads text and writes nothing to the file by default. -
-nan optionoptionalChanges the behaviour:-ncuts printing,-iwrites to the file,-Eturns on extended regexes,-eadds a command. -
/^port=/the addressoptionalSelects the lines: a number (3), a pattern (/^port=/), a range (2,5). Without an address, every line. -
sthe sed commandWhat to do with the line:sreplaces,ddeletes,pprints,a\appends after it. -
8080the patternA regular expression, between two/delimiters. -
9090the replacementThe text put in its place.&recalls the matched text. -
pthe flagoptionalRefiness:gfor every occurrence,2for the second one,Iignores case,pprints the replaced line. -
app.confthe fileoptionalOne or more files. Without a file,sedreads standard input, so the output of a pipe.
Outputport=9090
How sed reads a file, line by line
sed repeats the same cycle for each line: it reads it, applies the commands to it in order, then prints it. The map follows its working copy (the pattern space) on app.conf. Before clicking, note how many lines come out on screen and what app.conf contains: with no option, with -n, with -i, with both. Then check with the map.
Mental model
How sed processes a file
read a lineapply the commands, in orderprint and start again, line after line
Try Input · app.conf
The cycle
Pattern space
$ sed -e '/^#/d' -e 's/localhost/0.0.0.0/' app.conf
- sed reads line 1, “# serveur”, and copies it into the pattern space.
- /^#/d matches: the line is deleted from the pattern space. The cycle stops here, with nothing printed.
- sed reads line 2, “host=localhost”, and copies it into the pattern space.
- /^#/d does not match: the line does not start with #, so it stays.
- s/localhost/0.0.0.0/ matches: the first occurrence is replaced in the pattern space.
- End of the cycle: sed prints the pattern space, then moves to the next line.
- sed reads line 3, “port=8080”, and copies it into the pattern space.
- /^#/d does not match: the line does not start with #, so it stays.
- s/localhost/0.0.0.0/ does not match: nothing changes, and this is not an error.
- End of the cycle: sed prints the pattern space, then moves to the next line.
- No more lines to read. app.conf has not changed: the result is only displayed.
What the animation shows
- One line at a time.
seddoes not load the file into memory: it reads it as a stream, which also works on a huge file. - Every command, in order, on each line.
dstops the cycle: the following commands never see the line. - Printing is automatic, at the end of the cycle.
-ncuts it; you then needpto print a line. - The file does not change, except with
-i: the output then replaces the file.
Golden rules
Preview before editing in place
Run the command without -i, read the result, then add -i. Or keep a copy, which a second pass with the same suffix will overwrite:
sed -i.bak 's/a/b/' fileChange the delimiter when the text contains /
The character that follows s becomes the delimiter:
sed 's#/var/www#/srv/www#' site.confEssential vocabulary
Commands · in the script, between the quotes
s/old/new/- Replaces the first occurrence of the line
echo aaa | sed 's/a/b/'→ baa s/old/new/g- Replaces every occurrence
echo aaa | sed 's/a/b/g'→ bbb d- Deletes the line and moves to the next
sed '/^#/d' app.conf→ no comment left p- Prints the line (often with -n)
sed -n '2p' app.conf→ host=localhost
Options · on the command line, before the script
-n- Cuts automatic printing
sed -n '/port/p' app.conf→ port=8080 -i- Writes the result to the file
sed -i 's/8080/9090/' app.conf→ app.conf modified, empty screen -E- Extended regular expressions
sed -E 's/[0-9]+/N/' app.conf→ port=N on line 3 -e- Adds a command to the script
sed -e '/^#/d' -e 's/8080/9090/' app.conf→ two commands
Print lines with p and -n, stop with q
The p command (print) prints the selected line, but sed already prints every line by itself. Predict what this command gives:
sed 'p' paths.txt | head -4/usr/local/bin/app/usr/local/bin/app/etc/app/app.conf/etc/app/app.confp shows every line twice: the automatic print, then the p. The -n option turns off the automatic print: sed -n '2p' paths.txt prints only line 2. The q command stops sed after the current line (sed '2q' paths.txt), which avoids reading the rest of a file of several gigabytes.
Replace a word with s
The s command (substitute) is written s/old/new/: sed looks for old in each line and replaces it with new.
First occurrence, all occurrences
Line 2 of config.conf contains serveur twice; grep host keeps only that line.
sed 's/serveur/X/' config.conf | grep hostsed 's/serveur/X/g' config.conf | grep hosthost=X serveurhost=X XWith no option, sed replaces the first occurrence of each line. The g flag replaces them all, and a number (s/serveur/X/2) targets the second one.
Change the delimiter
The character right after s becomes the delimiter. With a path, the most natural command fails, because sed takes the first / of the path for the end of the pattern.
sed 's//usr/local//opt/' paths.txtsed: -e expression #1, char 8: unknown option to `s'sed read the empty pattern //, then usr, then local//opt/ as flags: character 8 is the l of local. Protect each slash with \/, or choose a character that appears neither in the pattern nor in the replacement: sed 's#/usr/local#/opt#' paths.txt replaces /usr/local with /opt and prints /opt/bin/app as its first line.
A substitution with no effect is not an error
If the pattern matches no line, sed says nothing and returns code 0.
sed 's/zzz/y/' config.conf > /dev/null; echo rc_sed=$?rc_sed=0A script that tests this code therefore believes the replacement happened. Check that a pattern finds something with sed -n '/zzz/p' config.conf (nothing comes out), or with sed -n 's/port=8080/port=9090/p' config.conf, which prints only the lines that were really replaced.
Chain several substitutions
A semicolon separates two commands of the same script, and -e passes them separately. sed applies them in order, to each line.
sed -e 's/usr/USR/' -e 's/var/VAR/' paths.txtLines 1 and 3 change (/USR/local/bin/app, /VAR/log/app.log), line 2 stays untouched.
Use a shell variable
Between single quotes, sed receives $valeur as it is. Between double quotes, the shell inserts the value, and two characters cause trouble:
valeur='R&D'; echo 'equipe=x' | sed "s/x/$valeur/"chemin='/opt/app'; echo 'racine=x' | sed "s/x/$chemin/"; echo "code $?"equipe=RxDsed: -e expression #1, char 6: unknown option to `s'code 1The & gives a wrong result with no message: in the replacement it stands for the matched text (\& for an ordinary &). The / closes the replacement too early, which another delimiter avoids (sed "s#x#$chemin#"). If you do not control the value, see "When to avoid sed".
Select lines with an address
An address goes in front of the command and limits its effect: 2s/serveur/X/ only changes line 2. It is tried here with d (delete), which removes the chosen lines from the output; no file is modified.
By line number
A number designates a line, two numbers separated by a comma a range (bounds included), $ the last line.
sed '2d' paths.txt removes line 2, /etc/app/app.conf, from the output and prints the two other paths.
By pattern
A pattern between / selects the lines that contain it. sed '/^#/d' config.conf removes the comments: the ^ anchor limits the pattern to lines that start with #, and without it a useful line followed by a comment would disappear too. The dot . accepts any character: /app.conf/ also matches appXconf, and \. aims at a real dot.
Everything except an address
A ! between the address and the command reverses it: sed '/app\.conf/!d' paths.txt deletes the lines that do not contain app.conf, and prints only /etc/app/app.conf.
Between two patterns
A range starts at a line that matches the first pattern and ends at the first following line that matches the second. Square brackets have a meaning in a pattern, so they are protected with \[ and \].
sed '/\[db\]/,/\[web\]/d' config.conf# configurationhost=serveur serveurport=8080port=80date=2026-11-24[cache]debug=falseBoth bounds are deleted with the range: [web] is gone, and port=80 ends up outside any section. To keep the end bound, group in braces a command that only targets the lines of the range: !d deletes those that do not contain [web], which gives sed '/\[db\]/,/\[web\]/{/\[web\]/!d}' config.conf.
A finished range reopens at every new start. If the second pattern matches no line, it runs to the end of the file, with no message and with code 0:
sed '/\[db\]/,/\[zzz\]/d' config.conf# configurationhost=serveur serveurport=8080With -i, the file would really be cut down to three lines. Before any deletion, print the range: sed -n '/\[db\]/,/\[zzz\]/p' config.conf.
Substitute on some lines only
In front of s, an address limits the replacement: sed '3s/port=.*/port=9090/' config.conf only touches line 3. With a range, only the lines of one section are concerned, and diff shows the change without printing eleven lines:
sed '/\[db\]/,/\[web\]/s/^port=.*/port=6543/' config.conf | diff config.conf -6c6< port=5432---> port=6543Only one line differs, the one in [db]: the two other port= lines do not move.
One line changed too many
A colleague wants to change the port of the [web] section from 80 to 8000 in config.conf. They run sed 's/port=80/port=8000/' config.conf | diff config.conf -, without -i to check first, and expected a single modified line. What do they see, why, and how do you change only the port of [web]?
Run the colleague's command, then fix it
sed 's/port=80/port=8000/' config.conf | diff config.conf -Count the lines diff reports and their value, then write a command that only changes the port of [web], with the same | diff config.conf -.
- sed s
- diff
- config.conf
I have tried: show the solution
3c3< port=8080---> port=8000808c8< port=80---> port=8000The pattern port=80 is not anchored: it also matches the start of port=8080, hence port=800080, with no message and with code 0. Two fixes give a single modified line, 8c8:
sed 's/port=80$/port=8000/' config.conf | diff config.conf -sed '/\[web\]/,/\[cache\]/s/port=80/port=8000/' config.conf | diff config.conf -The $ anchor requires port=80 to end the line. The range limits the change to [web]. In a bigger file, combine the two: the range and port=80$.
Reuse the matched text: & and groups
In the replacement, & stands for the text the pattern matched.
sed 's/port/[&]/' config.conf | head -3# configurationhost=serveur serveur[port]=8080The first two lines do not contain port and pass through as they are; the third shows [port].
Groups reorder pieces
With -E, parentheses form a group numbered from left to right, and \1, \2 put it back in the replacement.
sed -E 's/^([a-z]+)=(.*)$/\2=\1/' config.conf | head -3# configurationserveur serveur=host8080=portGroup 1 captures host, group 2 the rest of the line, and \2=\1 swaps them. The comment line does not match the pattern and stays untouched. The greediness of .* and the reordering of a date are covered in Regular expression basics.
Add a line
The a\ command appends text after the chosen line, i\ inserts before, c\ replaces it (table at the end of the lesson). To append delai=30 after line 2, only the start of the result is printed:
sed '2a\delai=30' config.conf | sed -n '1,4p'# configurationhost=serveur serveurdelai=30port=8080With a pattern as the address, anchor it: port=80 would also match port=8080, and the text would be appended after both lines. The text that follows a\ keeps its leading spaces, whereas a without a backslash strips them: prefer a\ in a file where indentation matters, a YAML file for example.
Edit a file in place with -i
The -i option (in place) saves the result into the file instead of printing it. Always run the command without -i first and read the output, then run it again with -i.
What -i does to the file
sed -i writes the result into a temporary file, then renames it over the original. This explains the symbolic link pitfall and the write permission on the folder, which -i needs to create that temporary file.
Keep a backup with -i.bak
A suffix glued to -i keeps the original under that name; without a suffix, nothing is kept. Work on a copy:
cp config.conf work.confsed -i.bak 's/8080/9090/' work.confecho work:; sed -n 3p work.confecho bak:; sed -n 3p work.conf.bakwork:port=9090bak:port=8080The suffix is glued to the option: with a space, sed -i .bak 's/80/90/' work.conf reads .bak as the script and fails with unknown command: `.'. For the same reason, -iE creates a file ending in E without turning on -E: write -Ei.
Edit several files at once
sed -i processes each file separately, like -s, and gives each one its backup. With neither -i nor -s, the numbering carries on from one file to the next: sed '1d' a.conf b.conf only removes line 1 of the first, sed -i '1d' a.conf b.conf that of both. To preview, add -s.
Pitfall: two passes overwrite the backup
Running sed -i.bak again on the same file replaces the .bak with the state from before the second pass: the original is lost, with no message. Exercise 2, in the section "Full case", has you practise it.
Pitfall: sed -i replaces a symbolic link
lien.conf is a link to config.conf. Edit it with -i, then compare:
sed -i 's/8080/9090/' lien.conf; ls -l lien.conf config.conf; sed -n 3p config.conf-rw-r--r-- 1 ansible ansible 123 Nov 24 19:37 config.conf-rw-r--r-- 1 ansible ansible 123 Nov 24 19:37 lien.confport=8080lien.conf starts with -: it has become an ordinary file, the link (which would start with l) is gone, and config.conf has not moved. To edit the target, add --follow-symlinks.
Pitfalls: -n with -i, q with -i, redirecting to the same file
With -n and p, sed -i only writes the lines that are printed; with q, only those read before it stops. A redirection empties the file being read:
cp paths.txt p3; sed 's/usr/USR/' p3 > p3; echo "code $?"; wc -c p3code 00 p3The shell runs > p3 before starting sed: the file is emptied and sed reads an empty file, with code 0. To write into the file being read, use -i.
Pitfall: -i is not written the same way on macOS and BSD
On macOS and FreeBSD, -i requires a backup extension (-i extension, see the FreeBSD manual of sed): the sed -i 's/a/b/' file of this lesson is not valid there. The form sed -i.tmp 's/a/b/' file && rm file.tmp works on both. Choose a suffix that is not the one of your backups: with -i.bak followed by rm file.bak, an existing backup would be deleted too.
Full case: edit a configuration file and be able to roll back
Three values change: the host, the user of the [db] section and the debug mode. You preview with diff file -, which compares the file with what arrives through the pipe.
cp config.conf web.confsed -e 's/^host=.*/host=web1/' \ -e '/^\[db\]/,/^\[web\]/s/^user=admin$/user=app/' \ -e 's/^debug=.*/debug=true/' \ web.conf | diff web.conf -2c2< host=serveur serveur---> host=web15c5< user=admin---> user=app11c11< debug=false---> debug=trueThree lines change, the ones you wanted, and web.conf has not moved. You then write the same command with -i.orig, and compare:
sed -i.orig -e 's/^host=.*/host=web1/' \ -e '/^\[db\]/,/^\[web\]/s/^user=admin$/user=app/' \ -e 's/^debug=.*/debug=true/' \ web.confdiff web.conf.orig web.confThe diff prints the same three differences as the preview. If the service rejects the file, the backup puts it back:
mv web.conf.orig web.conf; diff config.conf web.conf; echo "code $?"code 0diff prints nothing and returns 0: the file is back to its starting state. On a real server, edit the file under /etc: a file under /usr belongs to the package, whose update overwrites it.
Two passes without losing the original
In a copy of config.conf named e.conf, 8080 becomes 9090, then serveur becomes srv everywhere. You must be able to get back to the starting state. A colleague advises -i.bak on every pass: check what that gives, then do it without losing the original.
Observe
Copy config.conf to e.conf, run the two passes with -i.bak, then print lines 2 and 3 of e.conf.bak.
Preview
Copy config.conf to e.conf again, delete e.conf.bak, then print the two changes with diff without modifying e.conf.
Write and compare
Write the two sed -i commands so that the original stays under e.conf.orig, then compare e.conf.orig and e.conf and read the exit code of diff.
Restore and check
Put e.conf back to its original state from the backup, compare it with config.conf and read the exit code.
- sed -i
- diff
- cp
I have tried: show the solution
cp config.conf e.confsed -i.bak 's/8080/9090/' e.confsed -i.bak 's/serveur/srv/g' e.confsed -n '2,3p' e.conf.bakhost=serveur serveurport=9090The second pass replaced e.conf.bak: it holds the result of the first one (port=9090) and the original port=8080 is lost. The rest previews, then writes correctly:
cp config.conf e.conf; rm e.conf.baksed -e 's/8080/9090/' -e 's/serveur/srv/g' e.conf | diff e.conf -sed -i.orig 's/8080/9090/' e.confsed -i 's/serveur/srv/g' e.confdiff e.conf.orig e.conf; echo "code $?"mv e.conf.orig e.conf; diff config.conf e.conf; echo "code $?"2,3c2,3< host=serveur serveur< port=8080---> host=srv srv> port=90902,3c2,3< host=serveur serveur< port=8080---> host=srv srv> port=9090code 1code 0The suffix is only given on the first pass: the second one does not touch e.conf.orig, which keeps the state from before both passes. The first diff is the preview, the second returns 1 because the files differ, the last returns 0: e.conf is back to config.conf.
A file that came from Windows
A file created on Windows ends its lines with a carriage return (\r) followed by a line feed, and a substitution anchored on the end of the line no longer matches. cat -A makes hidden characters visible: $ marks the end of the line, ^M the carriage return.
cat -A dos.confsed 's/8080$/9090/' dos.conf | cat -Ased 's/\r$//' dos.conf | cat -Aport=8080^M$host=a^M$port=8080^M$host=a^M$port=8080$host=a$The second command changed nothing and reported no error: the last character of the line is the carriage return, not the 0. s/\r$// removes the ^M; add -i to save.
Which command should I use?
To find a syntax again, start from the need.
| I want to... | I write |
|---|---|
| Replace every occurrence, or the second one | s/old/new/g, s/old/new/2 |
| Ignore case, convert to uppercase | s/word/X/gI, s/.*/\U&/ |
| Substitute on one line, a range, the last line | 2s/a/b/, 2,3s/a/b/, $s/a/b/ |
| Delete lines, comments, empty lines | sed '2d', sed '/^#/d', sed '/^[[:space:]]*$/d' |
| Remove trailing blanks | sed 's/[[:space:]]*$//' |
| Print some lines, their numbers | sed -n '2,3p', sed -n '/pattern/=' |
| Insert before, replace a line | 2i\text, 2c\text |
| Edit the file, with a backup, on GNU and BSD | sed -i.bak 's/a/b/' f, sed -i.tmp 's/a/b/' f && rm f.tmp |
| Edit the target of a link, preview several files | sed -i --follow-symlinks 's/a/b/' link, sed -s '1d' a.conf b.conf |
When to avoid sed: JSON, YAML, XML and server state
sed sees lines of text, not a structure: a substitution that works on a test file breaks as soon as the order of the keys or the indentation changes. Prefer jq for JSON, yq (in French) for YAML, xmlstarlet to edit XML and awk for columns. In Ansible, a sed -i run by shell is replayed on every run and appends the line twice: the lineinfile module (in French) checks the state of the file first. To inject variables into a template, envsubst (in French) avoids the problems with / and &.
Troubleshooting
Always run the command again without -i, and check the pattern alone with sed -n '/pattern/p' file: if nothing comes out, the pattern matches no line.
| Message or symptom | Code | Likely cause | Solution |
|---|---|---|---|
sed: can't read fichier: No such file or directory | 2 | Wrong file name, or wrong folder | ls, pwd, run again from ~/sed-lab |
sed: -e expression #1, char 13: unterminated `s' command | 1 | The last delimiter is missing: s/serveur/srv | Write s/serveur/srv/ |
| No message, text unchanged | 0 | Case, $ on a Windows file, \d (read as the letter d), + without -E | cat -A to see ^M, [0-9], -E |
port=8080 becomes port=800080 | 0 | Unanchored pattern | Anchor with $, or limit to a range |
sed: couldn't open temporary file …: Permission denied | 4 | No write permission on the folder | sudo, or work on a copy |
A file ends with E after the command | 0 | -iE: the E is read as a suffix | -Ei |
sed returns 0 when it succeeded, even with no match, 1 for an invalid command, 2 for a missing file and 4 for an I/O error.
Clean up the practice folder
Delete the practice folder, that is ~/sed-lab and nothing else:
rm -r ~/sed-labKey points
sedwrites the result to standard output and only modifies the file with-i;-nturns off the automatic print.- With no match,
sreturns 0: check withsed -n '/pattern/p'. An unanchored pattern also finds a longer text (port=80inport=8080). - Both bounds of a range are deleted with it; with no end pattern, it runs to the end of the file.
-i.bakonly keeps the state from before the last pass,-iprocesses each file separately (preview with-s), and it replaces a symbolic link with an ordinary file.- In a variable,
&and/breaks; an invisible\rstops$from matching; on macOS and BSD,-irequires an extension. - For a configuration file: preview with
| diff file -, write with-i.orig, compare, andmvputs the old content back.
Knowledge check
Check that the essentials of this guide stuck. The questions cover only what has just been explained here.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: awk: filter, compute and group columns
A new full quiz with random questions
Work again only on the questions you missed
FAQ - Frequently Asked Questions
The questions most often asked about sed: what it does, replacing on a whole line, deleting lines, editing a file in place and keeping a backup.
-i.The commands to know
| Command | Action | Example |
|---|---|---|
s |
Replace text | sed 's/old/new/' file |
d |
Delete lines | sed '2d' file |
p |
Print lines, with -n |
sed -n '2p' file |
i, a, c |
Insert before, append after, replace a line | sed '2c\remplacé' file |
q |
Stop reading after a line | sed '2q' file |
sed are regular expressions, like those of grep. Always put the script between single quotes, so that the shell does not interpret $, * or \.When to choose another tool
sed does not understand any format: it only sees lines. To edit JSON, YAML or XML, use jq, yq or xmlstarlet instead. xmllint reads, formats and validates XML, but does not edit it.s/old/new/ replaces the first occurrence of each line and moves on to the next. The g flag (global), placed after the last /, replaces every occurrence in the line. A number in that place designates one precise occurrence.The three forms on the same line
The linehost=serveur serveur contains the word serveur twice:sed 's/serveur/X/' config.conf
sed 's/serveur/X/g' config.conf
sed 's/serveur/X/2' config.conf
On this line, the three commands give respectively:host=X serveur
host=X X
host=serveur X
When the text contains slashes
The character right afters becomes the delimiter. With a path, another delimiter avoids protecting each slash:sed 's#/usr/local#/opt#' paths.txt
If the pattern matches no line, sed prints no message and returns code 0. To check that a pattern finds something, print the lines it selects with sed -n '/pattern/p' file.d command chooses the lines to delete. A pattern between / selects the lines that contain it, and the original file stays intact as long as you do not add -i.Examples
| Need | Command |
|---|---|
| Remove comments | sed '/^#/d' config.conf |
| Remove empty lines and those that only contain blanks | sed '/^[[:space:]]*$/d' config.conf |
Keep only the lines that contain app.conf |
sed '/app\.conf/!d' paths.txt |
| Remove a section, bounds included | sed '/\[db\]/,/\[web\]/d' config.conf |
Remove a section but keep the [web] header that follows it |
sed '/\[db\]/,/\[web\]/{/\[web\]/!d}' config.conf |
^ anchor matters: /#/d would also delete any useful line followed by a comment, whereas /^#/d only targets lines that start with #. Likewise, /^$/d only removes truly empty lines, not those that contain spaces: it is [[:space:]]* that accepts spaces and tabs.The . of a pattern accepts any character: /app.conf/ also matches appXconf, whereas /app\.conf/ aims at a real dot. The ! reverses the selection: /app\.conf/!d deletes the lines that do not contain the pattern. Both bounds of a range are deleted with it, and if the end pattern matches no line, the range runs to the end of the file. Before deleting, print what the pattern selects with sed -n '/pattern/p' file.sed prints the result and does not touch the file. The -i option (in place) saves it into the file. Always run the command without -i first, read the output, then run it again with -i, preferably on a copy as long as you are not sure of the result.cp config.conf work.conf
sed 's/8080/9090/' work.conf
sed -i 's/8080/9090/' work.conf
The second command prints the result without touching the file. The third saves it into the file, printing nothing and keeping no copy of the old version.What -i really does
sed -i writes the result into a temporary file, then renames it over the original. The inode number of the file therefore changes, even if no line is modified. Consequence: if you edit a symbolic link, it is replaced with an ordinary file. The --follow-symlinks option edits the target of the link instead.Several files, and rolling back
With several files,-i processes each one separately: sed -i '1d' a.conf b.conf removes the first line of both, whereas sed '1d' a.conf b.conf removes only one. Add -s to preview. For a configuration file, preview with sed -e '…' file | diff file -, write with sed -i.orig -e '…' file, compare with diff file.orig file, and mv file.orig file puts the old content back.On macOS and BSD
The BSDsed requires an extension after -i (an empty extension is written -i ''). The form that is written the same way on GNU and BSD glues a throwaway suffix to the option, then deletes it:sed -i.tmp 's/a/b/' fichier && rm fichier.tmp
With -i.bak followed by rm fichier.bak, a fichier.bak that already existed would be overwritten then deleted: the .tmp suffix avoids losing a backup.-i keeps the original under that name. With -i.bak, sed keeps the original under the name file.bak and saves the modified version into file.Two pitfalls
- Two passes overwrite the backup. Run
sed -i.bak 's/9090/9191/' work.confagain:work.conf.baknow containsport=9090, and the original state (port=8080) is lost, with no message. If you chain several passes, copy the file withcpbefore the first one. - The suffix is glued to the option. With a space,
sed -i .bak 's/80/90/' filereads.bakas the script and answersunknown command, quoting the dot of.bak, with exit code 1. No backup is created.
sed reads patterns as basic regular expressions: groups are written \( and \). The -E option turns on extended expressions, where ( and ) are enough, and where + is written without a backslash.Groups and reuse of the matched text
In the replacement,& recalls the whole matched text, and \1, \2 recall the groups numbered from left to right. This command puts a date back in day/month/year format:sed -E 's/([0-9]{4})-([0-9]{2})-([0-9]{2})/\3\/\2\/\1/' config.conf | grep date
date=24/11/2026
Three pitfalls
- A
.*is greedy. Ona<b>c<d>e,s/<.*>//givesae, because.*extends up to the last>.s/<[^>]*>//ggivesace. - A
*accepts zero characters.s/[0-9]*/(&)/puts empty parentheses at the start of lines that do not begin with a digit.-E 's/[0-9]+/(&)/', or[0-9][0-9]*, requires at least one digit. \ddoes not mean a digit insed. GNU sed reads it as the letterd: use[0-9]or the POSIX class[[:digit:]]. A pattern that matches nothing produces neither an error nor a message.