How to replace only if whole line match pattern?

Example, input:

foo, bar, baz #
lorem, ipsum, ret

Example, output:

baz #
lorem, ipsum, ret

Should only replace commas with comma+newline if we have # at end of line.

1 Answer 1


Use the global command (:g) which runs specified commands on all matching lines:


This will do the substitution s/,/,\r/g on all lines that end with pound sign (/#$/). If you meant for it to be more specific just change the pattern between the first set of slashes. For example if you only wanted to apply this to lines that have two commas /^[^,]*,[^,]*,[^,]*#$/.

See :help :g.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.