I want to search lines beginning with certain string in Vim, and then add something at the end of file. I have tried the following but it removed everything instead of appending


This search all lines which begin with 12138 but it removes everything and add something_at_end_of_file

But I want to preserve actually string and add at end of line.

  • 1
    Do you want to add something of the lines matching ^12138 or at the end of the file?
    – padawin
    Commented Apr 26, 2019 at 11:04

3 Answers 3


use the :g command:


More information on :help :g

  • 1
    As an extra, :g has a sibling command: :v, which allows to run a command on every lines not matching a pattern.
    – padawin
    Commented Apr 26, 2019 at 12:04

You may try this:


That means:

%s substitute on all lines

/\v starts search pattern and uses very-magic mode, saves you from the need to escape everything (see :help \v)

^(12138.*) starting from the beginning of the line, find all text that starts with 12138 and is followed by anything else (.*) and put it into a group

/\1something_at_end_of_line/g replace the found patterns with the first group content and then add your text.


  • 1
    Good answer, but you don’t need the group (or the g flag). You can use either \0 or & to include the whole match in the replacement: :%s/12138.*/\0something_at_end_of_line
    – Rich
    Commented Apr 26, 2019 at 18:21

Another similar alternative: use :normal and Append in a :global command:


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.