Replace every occurrence of error with warn in app.log and print the result.
If a line contains error more than once, replace every occurrence without editing the source file.
Which command is correct?
The sed substitution command replaces a match. The trailing g flag applies it to every match on each line; without -i the input file is not modified.
Detailed explanation
sed 's/error/warn/' app.logIncorrect. Without g, sed replaces only the first match on each line.
Incorrect. Without g, sed replaces only the first match on each line.
sed 's/error/warn/g' app.logCorrect. The g flag replaces every error on every line and output goes to standard output.
Correct. The g flag replaces every error on every line and output goes to standard output.
tr 'error' 'warn' < app.logIncorrect. tr maps individual characters and does not perform the requested word substitution.
Incorrect. tr maps individual characters and does not perform the requested word substitution.
sed -n 's/error/warn/g' app.logIncorrect. -n suppresses normal output unless explicitly printed, so the transformed lines are not shown.
Incorrect. -n suppresses normal output unless explicitly printed, so the transformed lines are not shown.
Try it yourself
An example you can run in a temporary verification environment.
printf 'error then error
' | sed 's/error/warn/g'Expected result
warn then warnKey points
- The s/search/replacement/ form
- g means every match on a line
- Without -i the source is unchanged
Notes
- Environment: GNU sed 4.x
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.