How to edit text with sed in Linux
· Category: Linux
Short answer
sed is a stream editor that modifies text in a pipeline or file using simple commands.
Steps
- Replace text:
sed 's/foo/bar/g' file.txt
- Edit in place:
sed -i 's/foo/bar/g' file.txt
- Delete lines:
sed '/pattern/d' file.txt
- Replace on specific lines:
sed '3s/foo/bar/' file.txt
Tips
sed -i.bakcreates a backup before editing.- Use extended regex with
sed -E. - Escape delimiters if your pattern contains slashes:
sed 's|/usr/local|/opt|g'.
Common issues
sed -ibehavior differs between GNU and BSD/macOS versions.- Global replacement requires the
gflag; otherwise only the first match per line is replaced.