Replace every occurrence of error with warn in input.txt.
Print the result without modifying the original file.
Which command is appropriate?
sed s/OLD/NEW/g uses the g flag to replace every match on each line. Without -i, sed writes the result to standard output.
Detailed explanation
sed 's/error/warn/' input.txtIncorrect. Without g, sed replaces only the first match on each line.
tr 'error' 'warn' < input.txtIncorrect. tr maps individual characters, not a multi-character string.
cut -d error -f1 input.txtIncorrect. cut extracts fields and does not perform string replacement.
sed 's/error/warn/g' input.txtCorrect. sed 's/error/warn/g' replaces every per-line occurrence.
Try it yourself
An example you can run in a temporary verification environment.
printf 'error then error\n' | sed 's/error/warn/g'Expected result
warn then warnKey points
- s means substitute
- g means all matches per line
- The default output is stdout
Notes
- Environment: GNU sed 4.x / 標準入力
- Use small, disposable text streams when testing filters.
- Locale, encoding, and GNU/POSIX implementation details can affect edge cases.
Foundation review
Place the operation
A global substitution differs from the default first-match behavior while leaving the original input unchanged unless redirected.
Check the side effect
Print a before-and-after sample containing two matches on one line.