← Linux and the Command Line
Lesson 22 of 51 · 10 XP
sed — the stream editor
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
sed edits text "on the fly", line by line. Its main command is substitution, s:
sed 's/cat/dog/' file # the first cat in each line becomes dog
sed 's/cat/dog/g' file # all of them (g — global)
sed 's/cat/dog/gi' file # ignoring case (GNU)
sed -i 's/8080/9090/g' app.conf # -i — change the file itself (in-place)
Other commands:
sed -n '5p' file # print only line 5 (-n — don't print the rest)
sed -n '2,4p' file # lines 2 to 4
sed '/^#/d' file # delete comment lines
sed '/^$/d' file # delete empty lines
The separator in s can be any character. That's handy for paths: sed 's|/usr/local|/opt|g'.
Groups and references to them (-E — the extended syntax):
echo "Kai Ivanov" | sed -E 's/(\w+) (\w+)/\2 \1/' # Ivanov Kai
Task. The input is a configuration file. Delete the comment lines (they start with #) and the empty lines, and in the remaining ones replace localhost with 127.0.0.1.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.