Linux Command: sed
Stream editor for filtering and transforming text
sed (stream editor) is a powerful non-interactive text editor that processes text line by line. It is primarily used for find-and-replace operations, text transformations, and line-level editing in files and pipelines. sed reads input, applies editing commands, and writes the result to standard output โ the original file is unchanged unless -i (in-place) is used. This makes sed safe for testing transformations before applying them. It supports basic and extended regular expressions for complex pattern matching. Common uses include substituting text, deleting lines, inserting content, and transforming configuration files. sed is particularly valuable in shell scripts and automation pipelines where interactive editing is not possible.
Syntax
sed [OPTION]... 'SCRIPT' [FILE]...Key Options
-iโ Edit files in place (modify the original file)-i.bakโ Edit in place with backup-eโ Add multiple editing commands-nโ Suppress automatic output (use with p command)-E (-r)โ Use extended regular expressionss///gโ Substitute command with global flag (replace all)
Examples
Simple find and replace
sed 's/foo/bar/g' input.txtIn-place edit with backup
sed -i.bak 's/localhost/192.168.1.100/g' config.ymlDelete comment lines
sed '/^#/d' /etc/ssh/sshd_configPro Tips
- Run sed without -i first to preview changes in stdout. Only add -i when confident the result is correct, or use -i.bak for safety.
- When patterns contain slashes (like file paths), use a different delimiter: sed 's|/var/www|/srv/http|g' avoids escaping slashes.
- For complex regex with lookaheads/lookbehinds not supported in sed, use perl -pe 's/pattern/replacement/g' instead.
Learn more: Full sed reference โ