A
cd ..
Tools

Sed Stream Editor Basics

Text manipulation and find-replace operations with sed.

2025-09-03
sed, text-processing, linux

Replace first occurrence in line

sed 's/old/new/' file.txt

Replace all occurrences (global)

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

Edit file in-place

sed -i 's/old/new/g' file.txt

macOS requires -i '':

sed -i '' 's/old/new/g' file.txt

Delete lines containing pattern

sed '/pattern/d' file.txt

Delete empty lines

sed '/^$/d' file.txt

Delete line number 5

sed '5d' file.txt

Delete lines 5-10

sed '5,10d' file.txt

Print only lines containing pattern

sed -n '/pattern/p' file.txt

Replace on specific line (line 3 only)

sed '3s/old/new/' file.txt

Add line after match

sed '/pattern/a New line here' file.txt

Multiple substitutions

sed -e 's/foo/bar/g' -e 's/hello/world/g' file.txt

Use different delimiter (useful with paths)

sed 's|/old/path|/new/path|g' file.txt

Capture groups

Replace "John Doe" with "Doe, John":

sed 's/\([A-Z][a-z]*\) \([A-Z][a-z]*\)/\2, \1/' file.txt

Was this useful?

Share with your team

Browse More