Linux and Command-Line Basics
$ echo "aaa bab" | sed 's/a/x/'Which of the following is the output of the sed command above, which replaces characters?
- Axaa bab
- Bxaa bxb
- Cxxx bxb
Show answer and explanation
Answer: A. xaa bab
sed's s/before/after/ replaces only the first match found on each line. The first a on this line is the first character, so the output is xaa bab. To replace every match on the line, add g (global) at the end, as in s/a/x/g, which outputs xxx bxb. Replacement works line by line, so if a file has several lines, the first match on each line is replaced even without g.
- A. Correct. Without g, only the first a on the line becomes x.
- B. Replacement is done per line, not per word. Without g, only the first match on the line is replaced.
- C. This is the output with g added, as in s/a/x/g.