Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

How to Use the Linux sed Command to Edit Text

Use sed to replace text, print a line range, filter input, and make an in-place edit with a backup.

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.

What is Sed? Learn about the Sed command in Linux Picture 1

Replace text

sed 's/old/new/' notes.txt
sed 's/old/new/g' notes.txt

The 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.

sed -n '5,10p' notes.txt
sed '/^#/d' notes.txt

The 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.

What is Sed? Learn about the Sed command in Linux Picture 2
sed applies editing commands to text read from a file or input stream.

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.txt

Use 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.txt

On 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.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.