Script Valley
Linux & Bash for Developers
Text Processing & SearchingLesson 2.4

sed command for find and replace in Linux

sed syntax, s command, g flag, -i in-place editing, address ranges, delete lines, print specific lines, regex in sed

sed: Stream Editor for Transforming Text

sed processes text line by line and applies editing commands. Its most common use is find-and-replace, but it can delete lines, extract ranges, and apply regex transformations — all without opening a file in an editor.

The Substitute Command

The core syntax is s/pattern/replacement/flags. By default sed replaces only the first match per line. Add g to replace all occurrences on each line. Add i for case-insensitive matching.

# Replace first occurrence on each line
sed 's/localhost/production.server.com/' config.txt

# Replace ALL occurrences on each line
sed 's/http:/https:/g' urls.txt

# Edit file in-place (modify the actual file)
sed -i 's/DEBUG/INFO/g' app.conf

# Create a backup before editing in-place
sed -i.bak 's/old_value/new_value/g' config.env

Delete and Print Lines

# Delete lines containing a pattern
sed '/^#/d' config.txt       # remove comment lines
sed '/^$/d' file.txt         # remove blank lines

# Print only lines 5 through 10
sed -n '5,10p' large_file.txt

# Print lines matching a pattern
sed -n '/ERROR/p' app.log

The -i.bak pattern is essential for production use: it edits the file in place but saves the original with a .bak extension. Always use it when modifying config files via scripts.

Up next

awk command tutorial for text processing

Sign in to track progress