David Y. Stephenson
David Y. Stephenson

Reputation: 970

Vim: Search for patterns and add text to end of each line where it occurs

I would like to search for a pattern in vim, and on each line where it occurs, add text to the end of the line. For example, if the search pattern is print( and the text to add is ):

from __future__ import print_function
print('Pausing 30 seconds...'
print("That's not a valid year!"

should become

from __future import print_function
print('Pausing 30 seconds...')
print("That's not a valid year!")

Upvotes: 7

Views: 5329

Answers (2)

kenorb
kenorb

Reputation: 166319

To add text to the end of a line that begins with a certain string, try:

:g/^print(/s/$/)

See: Power of g - Examples for further explanation.

Upvotes: 1

Kent
Kent

Reputation: 195029

this command should do it for you:

:g/print(/norm! A)

what it does:

:g/print(/   "find all lines matching the regex
norm! A)     "do norm command, append a ")" at the end of the matched line.

you may want to check

:h :g

for details.

Upvotes: 12

Related Questions