sed command in Linux: stream text editing
Updated November 1, 2026
The sed command edits text line by line on the fly, most often substituting by pattern.
Syntax
sed 's/pattern/replacement/flags' fileCommon cases
sed 's/DEBUG/INFO/' log # replace the first match on a line
sed 's/DEBUG/INFO/g' log # g: every match on the line
sed -n '1,10p' file # print lines 1 to 10
sed -i 's/foo/bar/g' file # -i: edit the file in placeSample output
$ cat pair.txt
host=localhost port=5432 backup=localhost
$ sed 's/localhost/db/' pair.txt
host=db port=5432 backup=localhost
$ sed 's/localhost/db/g' pair.txt
host=db port=5432 backup=db
$ cat pair.txt
host=localhost port=5432 backup=localhostHow it works: a stream, not an editor
sed(stream editor) reads line by line, applies its commands, and writes the result to standard output - the file itself is untouched. Sosed 's/.../.../' fileis safe to preview before you add-i. The-iflag rewrites the file in place, and a mistake there is irreversible: run it without-ifirst, or use-i.bakto keep a backup copy. The pattern ins///is a regular expression.
Common mistakes
A slash inside the pattern breaks s///. The command sed 's//usr/local//opt/local/' never runs: sed answers sed: -e expression #1, char 8: unknown option to and then names the s command. It took the first slash inside the path as the end of the pattern. Any character can be the delimiter in s, so paths get rewritten like this: sed 's#/usr/local#/opt#'.
On the right side of s/// the & sign stands for the whole match. echo 'connection refused' | sed 's/refused/[&]/' prints connection [refused], not connection [&]. To get a literal ampersand, escape it: s/refused/[\&]/.
sed 's/DEBUG/INFO/g' app.log > app.log destroys the file. The shell empties app.log for the redirect before sed starts reading it, and 0 bytes are left. Use -i to edit in place, and a different name when you want the result in another file.
Used in
You need this in the lesson Text: grep, sed, awk. The theory is the chapter Bash in depth.
See also
The grep command, The awk command, Regular expressions.
Try it
Open the sandbox: a real throwaway Linux terminal in your browser. Run the commands above by hand - the container is deleted when you leave.