How to Use the sed Command for Text Editing
The sed command (stream editor) reads text and applies editing instructions. Its most common job is find-and-replace: sed 's/old/new/g' file replaces every old with new. It prints the result to the screen, or you can write it back to the file with -i.
Substitute text with s/old/new/
The substitution command has the form s/pattern/replacement/. By default it changes only the first match on each line; add g to change every match.
Edit the file in place with -i
sed prints to stdout by default. Add -i to edit the file directly. On macOS use -i "" to skip creating a backup copy.
Target specific lines
Prefix the command with a line number or range. 2d deletes line 2, 1,5d deletes lines 1 through 5, and /pattern/d deletes every line that matches.
The last example removes every comment line that starts with #, which is handy for stripping config files.
Print only matching lines with -n
Use -n to suppress normal output and p to print only what matches. This works like a focused grep.
Chain edits with -e
Apply several instructions in one pass with -e. This replaces old with new and deletes blank lines in a single read of the file.
sed is one of the three classic text tools alongside awk. The sed reference page documents the full command language.
Keep learning
Related guides: awk: The Linux Text Processing Tool Explained · How to Search Files for Text with the Linux grep Command · Linux Redirection and Pipes: A Practical Guide. Read all tutorials on the Learn Linux blog.