Updated: 3 November 2026 · Applies to: GNU sed
sed (stream editor) performs text transformations on a file or input stream without opening it in an editor, most commonly to find and replace text. These examples all assume a file named test.
Replace the first match on each line
sed 's/system/software/' test
By default sed replaces only the first match per line. The pattern breaks down as: s starts a substitution, / separates the three parts (search pattern, replacement, flags), system is what to search for, and software is what to replace it with.
Replace every match on each line
Add the g (global) flag:
sed 's/system/software/g' test
Replace only the Nth match on a line
sed 's/system/software/2' test
Replace on one specific line number
sed '3 s/system/software/' test
Replace across a range of lines
sed '3,$ s/system/software/' test
$ means the last line, so this covers line 3 through the end of the file.
Replace only on lines matching a pattern
sed '/vital/ s/system/software/' test
Use a different delimiter
Useful when the search pattern or replacement itself contains a slash, for example a URL or file path:
sed 's|/var/www|/srv/www|' test
Any character can be the delimiter, as long as it is used consistently in that command; |, _ and @ are all common choices.
Reference the matched text in the replacement
& stands for whatever the pattern matched:
sed 's/system/[&]/' test
This wraps every match in square brackets instead of replacing it outright.
Print the replaced line, then filter to only changed lines
The p flag prints the line again after a successful replacement, which, combined with -n to suppress sed's normal automatic printing, shows only the lines that actually matched and changed:
sed -n 's/system/software/p' test
Use sed like grep
Print only lines matching a pattern, with no substitution at all:
sed -n '/vital/ p' test
Print only lines that do not match, the equivalent of grep -v:
sed -n '/vital/ !p' test
Delete lines
Delete one specific line:
sed '2 d' test
Delete a range of lines, here from line 2 to the end:
sed '2,$ d' test
Use sed like tr, translating characters
sed 'y/AT/at/' test
The y command maps each character in the first set to the character in the same position in the second set; here, every A becomes a and every T becomes t.
Run several sed commands at once
sed -e 's/An/The/' -e 's/is/was/' test
Edit the file in place
By default sed only prints its output; it does not touch the original file unless you tell it to with -i:
sed -i 's/system/software/' test
Edit in place, keeping a backup first
sed -i.bak 's/system/software/' test
This saves the original as test.bak before making the change, which is worth doing by default for anything you cannot easily reconstruct.
Case-insensitive matching
sed is case-sensitive by default. Add the I flag for a case-insensitive search:
sed 's/system/software/I' test