The current vi line contains old several times.
Replace every old on the current line with new, leaving other lines unchanged.
Which ex command is correct?
:s targets the current line by default. Its trailing g flag replaces every match on that line.
Detailed explanation
:s/old/new/gCorrect. It replaces every old on the current line with new.
Correct. It replaces every old on the current line with new.
:s/old/new/Incorrect. Without g, only the first match on the current line is replaced.
Incorrect. Without g, only the first match on the current line is replaced.
:%s/old/new/Incorrect. % selects all lines, while the requirement is limited to the current line.
Incorrect. % selects all lines, while the requirement is limited to the current line.
:g/old/new/Incorrect. :g selects lines matching a pattern but this is not the substitute syntax.
Incorrect. :g selects lines matching a pattern but this is not the substitute syntax.
Try it yourself
An example you can run in a temporary verification environment.
printf 'old and old\nold next\n' > sample.txt; vim -Nu NONE -n -es sample.txt -c '1s/old/new/g' -c 'wq'; cat sample.txtExpected result
new and new
old nextKey points
- :s targets the current line
- g means every match on the line
- :%s targets all lines
Notes
- Environment: Vim 9.x(vi互換exコマンド)
- 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.