← Files & Text
Linux · Files & Text

How to search and replace text with sed in Linux

Replace text in a stream or file with sed, preview before editing, and edit in place safely with a backup.


Replace text with sed. By default it prints to stdout, which is safe to preview; -i writes changes back to the file.

sed -i edits the file in place. Run it without -i first to preview, and use -i.bak to keep a backup, since the change cannot otherwise be undone.

# Preview: print with replacements (does not change the file)
sed 's/old/new/g' <file>

# Print only the changed lines
sed -n 's/old/new/gp' <file>

# Edit in place, keeping a .bak backup
sed -i.bak 's/old/new/g' <file>

# Delete lines matching a pattern (preview first)
sed '/pattern/d' <file>
LinuxsedText