Table of Contents
sed is a stream editor. It reads text from a file or standard input, applies a script, and writes the result to standard output. By default it leaves the source file intact, so you can preview changes before saving them.

Replace text
sed 's/old/new/' notes.txt
sed 's/old/new/g' notes.txtThe first command replaces the first match on each line. Adding g replaces every match on each line. The search pattern is a regular expression. You can use a different delimiter to simplify editing paths, as in sed 's|/old/path|/new/path|g' notes.txt.
Print a section or remove matching lines
sed -n '5,10p' notes.txt
sed '/^#/d' notes.txtThe first command prints lines 5 through 10. -n suppresses normal output so only the lines selected by p appear. The second command drops lines that start with # from the output.

Read from a pipe or save the result
printf '%s
' 'status: draft' | sed 's/draft/final/'
sed 's/old/new/g' notes.txt > updated-notes.txtUse a new output filename when redirecting. Redirecting back into the input file can truncate it before sed reads it.
Edit a file in place with a backup
sed -i.bak 's/old/new/g' notes.txtOn GNU sed and common BSD versions this changes notes.txt and saves the previous contents to notes.txt.bak. Preview the same script without -i.bak first. See the GNU sed options for GNU-specific behavior. On another system, man sed describes the installed version. Use command -v sed to see whether the command is available.
Reader Comments 0
Sign in with email or Google to join the discussion.