sed -i.bak 's/old/new/g' file.txt

sed Command Builder

sed does one thing well and its syntax makes that hard to remember. Pick an operation, set the pattern, and get a command that will not eat your file.

Run it without -i first

sed -i rewrites the file with no confirmation and no undo. Run the same command without -i to print the result to your terminal, confirm it is what you meant, and only then add the flag. Two other traps: use a delimiter your pattern does not contain, so replacing a path becomes s|/usr/local|/opt| instead of a wall of escaped slashes; and an unanchored pattern matches everywhere, so s/user/admin/g will happily rewrite username and superuser too.

Build sed find and replace commands

This sed builder generates substitution, deletion, print, insert, and append commands with the flags people forget: g for every match on a line rather than the first, I for case insensitivity, -E for extended regular expressions, and -i with a backup suffix for in-place editing. It picks a delimiter that avoids escaping slashes in paths and shows the preview form so you can check the result before overwriting anything.

sed FAQ

Why does sed -i behave differently on macOS?

GNU sed treats the backup suffix as optional, so -i alone edits in place. BSD sed, which macOS ships, requires an argument, so -i alone consumes the next word as the suffix and fails confusingly. Use -i.bak on both, or -i '' on macOS specifically.

When should I use awk instead?

sed operates on lines as text streams and is best at substitution and line selection. awk understands records and fields, so anything involving columns, arithmetic, or accumulating state across lines is an awk job. Replacing a string is sed; summing the third column is awk.

How do I replace only the first match in the whole file?

Drop the g flag to get the first match per line, then restrict to the first matching line: sed '0,/pattern/s//replacement/' file. The empty pattern in the substitution reuses the address pattern.

Why is my regex not matching?

Basic regular expressions, the default, require backslashes before +, ?, |, (, and ). Extended regex with -E treats them as operators directly, which is what most people expect from other tools. If a pattern that works in grep -E fails in sed, add -E.