LFCS · Question #804
Which of the following commands replaces each occurrence of 'bob' in the file letter with 'Bob' and writes the result to the file newletter?
The correct answer is D. sed 's/bob/Bob/g' letter > newletter. This question tests the use of sed for global string replacement within a file and redirecting the output to a new file.
Question
Options
- Ased '/bob/Bob' letter > newletter
- Bsed s/bob/Bob/ letter < newletter
- Csed 's/bob/Bob' letter > newletter
- Dsed 's/bob/Bob/g' letter > newletter
- Esed 's/bob, Bob/' letter > newletter
How the community answered
(31 responses)- B3% (1)
- C6% (2)
- D87% (27)
- E3% (1)
Why each option
This question tests the use of `sed` for global string replacement within a file and redirecting the output to a new file.
`sed '/bob/Bob'` is an invalid `sed` command for substitution; it would attempt to match lines containing 'bob' and then interpret 'Bob' as another command.
`sed s/bob/Bob/` is missing single quotes around the `sed` expression, and `< newletter` would attempt to take input from `newletter`, not write output to it.
`sed 's/bob/Bob'` performs substitution only for the *first* occurrence of 'bob' on each line, not every occurrence as required.
The `sed 's/old/new/g'` command performs a global substitution on each line, replacing all occurrences of 'old' with 'new'. The 'g' flag after the substitution pattern is crucial for replacing every instance of 'bob' on a line, and `> newletter` redirects the standard output of the `sed` command to the specified file 'newletter'.
`sed 's/bob, Bob/'` is an incorrect substitution syntax, using a comma instead of the second `/` and lacking a replacement string after the second delimiter.
Concept tested: sed global string replacement and output redirection
Source: https://man7.org/linux/man/man1/sed.1.html
Topics
Community Discussion
No community discussion yet for this question.