To replace a string in a file with sed, run sed -i 's/old/new/g' file.txt. The s command swaps old for new, the g flag does it for every match on a line, and -i writes the result back into the file instead of printing it.
The examples below use GNU sed, which is what most Linux distributions ship. macOS and BSD differ in one important way, covered further down.
The basic command
sed -i 's/old/new/g' file.txt
Read the quoted part as s/regexp/replacement/flags. sed reads the file line by line, and on every line it replaces text matching the regular expression with the replacement. The single quotes stop the shell from interpreting characters such as $ and * before sed sees them.
Without -i, the same command only prints the edited text and leaves the file alone. That makes it a safe preview:
sed 's/old/new/g' file.txt
Run the preview first, check the output, then add -i.
Replace the first match or all matches
By default, s replaces only the first match on each line. Given a file demo.txt with this content:
cat dog cat dog
cat bird cat
Compare the three variants. Output is example output.
sed 's/cat/fox/' demo.txt
fox dog cat dog
fox bird cat
sed 's/cat/fox/g' demo.txt
fox dog fox dog
fox bird fox
sed 's/cat/fox/2' demo.txt
cat dog fox dog
cat bird fox
The GNU manual describes g as applying the replacement to all matches, and a number as replacing only that numbered match. In POSIX terms, the number replaces the nth occurrence on the line and g replaces all non-overlapping instances. In GNU sed you can combine them: s/cat/fox/2g replaces the second match and every one after it.
Edit the file in place, with a backup
GNU sed's -i takes an optional suffix attached directly to the option. If you give one, sed keeps a copy of the original under that suffix:
sed -i.bak 's/old/new/g' file.txt
This leaves file.txt edited and file.txt.bak holding the original text. Without a suffix, the GNU manual says the original file is overwritten with no backup. The FreeBSD manual goes further and advises against an empty extension, because a failure such as a full disk can leave a corrupted or partial file. A backup suffix costs one line and is cheap insurance for anything you cannot recreate. If the file is under version control, the repository serves the same purpose.
Two details from the GNU manual are worth knowing:
-iimplies-s, so with several files each one is treated separately. Line numbers restart at 1 in every file, and$means the last line of each file.- If the target is a symbolic link, the default is to break the link and replace it with a regular file, so the link's destination is not modified. Add
--follow-symlinksif you want to edit the destination.
macOS and BSD: the empty-extension argument
The POSIX sed specification (the 2017 edition I checked) defines only -e, -f and -n, so in-place editing is an extension, and implementations disagree. On macOS and other BSD systems, -i takes the extension as a separate argument. To edit without a backup there, pass an empty string:
sed -i '' 's/old/new/g' file.txt
sed -i .bak 's/old/new/g' file.txt
The FreeBSD manual says a zero-length extension means no backup is saved. If you run the GNU form sed -i 's/old/new/g' file.txt on BSD sed, it reads s/old/new/g as the extension and then treats file.txt as the script, so you get an error instead of an edit. One portable habit is to write -i.bak everywhere and delete the backups afterwards, but check this on your own systems, because behavior of the attached form differs between versions. Another is to install GNU sed on macOS and use that.
Replace in many files at once
Pass several files, or use a shell glob:
sed -i 's/old/new/g' *.conf
To search a directory tree, combine it with grep -l or find, so that only files containing the string are touched:
grep -rl 'old' ./src | xargs sed -i 's/old/new/g'
find ./src -type f -name '*.txt' -exec sed -i 's/old/new/g' {} +
For file names that may contain spaces, use grep -rlZ with xargs -0. Our guides to grep examples and the find command cover those options in detail. Run a dry run with grep -rl 'old' ./src first to see exactly which files will change.
Use a different delimiter when the text has slashes
The GNU manual states that the / characters in s can be replaced uniformly by any other single character. That removes the need to escape paths:
sed -i 's|/usr/local/bin|/opt/bin|g' config.txt
sed -i 's#http://#https://#g' links.txt
Choose a delimiter that appears in neither the pattern nor the replacement. Pipe, hash and comma are common choices.
Special characters: &, \1 and escaping
In the replacement, an unescaped & stands for the entire matched text. POSIX says the same, and that a backslash before it (\&) makes it a literal ampersand.
echo 'price 10' | sed 's/[0-9]\+/[&]/'
price [10]
echo 'fish & chips' | sed 's/&/and/'
fish and chips
echo 'fish and chips' | sed 's/and/\&/'
fish & chips
The output above is example output. Note that the first command uses \+, a GNU extension to basic regular expressions meaning "one or more". The pattern & in the second command needs no escaping, since the special meaning applies only to the replacement.
Capture groups and extended regex
Parentheses capture part of a match, and \1 to \9 in the replacement refer back to them. With the default basic regular expressions, groups are written \(...\). Adding -E (or -r in GNU sed) switches to extended regular expressions, where plain (...) works:
echo 'Smith, Jane' | sed -E 's/([A-Za-z]+), ([A-Za-z]+)/\2 \1/'
Jane Smith
The GNU manual notes that -E is accepted by BSD seds and is now in POSIX, but the POSIX 2017 page I opened does not list it, so treat it as widely supported rather than universal. A caution on combining options: sed -Ei means -E -i, while sed -iE uses E as the backup suffix and quietly leaves you with basic regexes. Put -i last or write the options separately.
Case-insensitive and other flags
These s flags come from the GNU manual:
| Flag | Effect |
|---|---|
g | Replace all matches on the line, not just the first |
2 (any number) | Replace only that numbered match |
I | Match case-insensitively (GNU; lowercase i is not used for this in sed) |
p | Print the new line if a substitution was made |
w file | Write the line to a file if a substitution was made |
M | Multi-line mode, where ^ and $ also match around embedded newlines |
For example, sed -i 's/error/warning/Ig' app.log changes Error, ERROR and error alike. The e flag, which runs the result as a shell command, exists in GNU sed but is almost never what you want here.
Limit the replacement to certain lines
Put an address before the command to restrict where it applies:
sed -i '5s/old/new/' file.txt
sed -i '10,20s/old/new/g' file.txt
sed -i '/^server/s/80/8080/' file.txt
The first changes only line 5, the second lines 10 to 20, and the third only lines starting with server. Use -e to run several substitutions in one pass: sed -i -e 's/a/b/' -e 's/c/d/' file.txt.
Mistakes that damage files
- Using -n with -i. The GNU manual gives
sed -ni 's/foo/bar/' FILEas a wrong example:-nsuppresses output, and in-place mode writes that (empty) output back, so the file is truncated. Also,-nimakesian option, but-inwould makenthe suffix. Always keep these options separate. - Redirecting onto the input file.
sed 's/a/b/' file.txt > file.txtempties the file before sed reads it. Use-i, or write to a different file. - Unescaped regex characters. In a basic regular expression,
.and*are special. To replace a literal1.5, write1\.5, or the pattern also matches125. - Double quotes around the script. Inside double quotes the shell expands
$variable, which is useful for passing a value in but dangerous with untrusted text that contains slashes or newlines.
If the replacement does nothing
Run the command without -i and look at the output. If nothing changed, the pattern did not match: check case (add I), regex special characters, and whether the file uses Windows line endings, since a trailing carriage return can stop a pattern ending in $ from matching. If sed prints an error about an unterminated s command or an unknown option to s, a delimiter character appears inside your pattern or replacement; switch to another delimiter.
Frequently asked questions
- How do I replace a string in a file with sed without changing the original?
- Leave out -i and redirect the output to a new file: sed 's/old/new/g' input.txt > output.txt. Without -i, sed only writes the edited text to standard output, so the original file is not touched. Do not redirect to the same file you are reading, because the shell empties it before sed starts.
- Why does sed -i not work on macOS?
- macOS ships a BSD sed, whose -i option expects an extension argument. GNU sed treats the suffix as optional and attached to the option. On BSD sed, pass an empty extension as a separate argument, sed -i '' 's/old/new/g' file, to edit without a backup.
- How do I replace a string that contains slashes?
- Use a different delimiter for the s command, because any single character can replace the slash. For example, sed 's|/usr/local|/opt|g' file works without escaping any slashes. Pick a character that does not appear in your pattern or replacement.
- Does sed replace every match on a line?
- No. Without the g flag, s replaces only the first match on each line. Add g to replace all matches, or a number such as 2 to replace only the second match.