sed: find and replace text in multiple files (sed -i)
Replace text in one file or many files with sed -i, make a backup first, and avoid the macOS and special-character mistakes.
sed edits text with an s command: s/old/new/ replaces the first match on each line, and s/old/new/g replaces every match. Add -i to change the file in place instead of printing the result.
Replace text in many files, step by step
- Try it without -i first: sed 's/old/new/g' file.conf. It prints the result and changes nothing.
- Back up with a suffix: sed -i.bak 's/old/new/g' file.conf.
- For many files, list them with find and pass them to sed (below).
- Check the result with grep -rn new . and compare with the .bak files.
Commands you can copy
sed 's/old/new/g' file.confsed -i.bak 's/old/new/g' file.confsed -i 's/old/new/g' file.conffind . -type f -name '*.conf' -exec sed -i.bak 's/old/new/g' {} +sed -i '' 's/old/new/g' file.confsed -i 's|/old/path|/new/path|g' file.confsed -E 's/(foo|bar)/baz/g' file.confOptions and traps
- -i[SUFFIX]
- Edits the file in place. If you add a suffix, such as -i.bak, sed keeps a backup with that ending. There is no space between -i and the suffix.
- -E
- Uses extended regular expressions, so you can write (a|b) and + without backslashes. The sed manual calls -E the portable form.
- -n
- Suppresses automatic printing. Used with a p command to print only matching lines.
- & in the replacement
- In the replacement part, & stands for the text that matched. To write a literal ampersand, escape it as \&.
- macOS error: invalid command code
- macOS uses BSD sed, where -i needs an argument. Write -i '' for no backup, or -i .bak.
- Slashes in paths
- Pick another delimiter, such as s|/old/path|/new/path|g, instead of escaping every slash.
- Special characters
- In the pattern, characters such as . * [ ] are special. Escape a literal dot as \..
- Config files
- For generating a config from scratch, our config generators may be faster than editing by hand.
Questions about sed replace text in files
- How do I replace text in all files in a folder?
- Use find with -exec sed -i, as in the commands above. Run it without -i on one file first.
- How do I make a backup before sed -i?
- Add a suffix: sed -i.bak. The original is saved with that ending.
- Why does sed -i work on Linux but not on macOS?
- macOS ships BSD sed, which requires an argument after -i. Use -i '' or -i .bak.
- What does the g at the end mean?
- It replaces every match on a line, not only the first.