Linux LFCS Exam: Replace Occurrences of 'bob' in File - Commands and Examples

Replace 'bob' with 'Bob' in File and Write to newletter

Question

Which of the following commands replaces each occurrence of 'bob' in the file letter with 'Bob' and writes the result to the file newletter?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D. E.

D

The correct answer is D. sed 's/bob/Bob/g' letter > newletter

Explanation:

The sed command is a stream editor used to perform text transformations on an input stream (file or pipeline). The syntax of the sed command is sed [options] 'command' file(s).

In this case, we want to replace each occurrence of 'bob' in the file letter with 'Bob' and write the result to the file newletter.

The correct command is:

sed 's/bob/Bob/g' letter > newletter

Here's what each part of the command does:

  • sed: invokes the stream editor.
  • 's/bob/Bob/g': the command to replace every occurrence of 'bob' with 'Bob' in the file.
    • s: the substitute command tells sed to substitute one string for another.
    • /: delimits the search and replace strings.
    • bob: the search string to be replaced.
    • /: delimits the search string from the replacement string.
    • Bob: the replacement string to be substituted.
    • /: delimits the replacement string from the options.
    • g: the global option tells sed to replace all occurrences of the search string in each line, not just the first occurrence.
  • letter: the name of the input file to be edited.
  • >: redirects the output of the sed command to a file.
  • newletter: the name of the output file to write the edited text to.

Therefore, the correct answer is D. sed 's/bob/Bob/g' letter > newletter