1

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

:%s/^12138/*something_at_end_of_file/g

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
  • 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

5

use the :g command:

:g/^12138/s/something-at-the-end$/something-new-at-the-end/

More information on :help :g

1
  • 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
3

You may try this:

%s/\v^(12138.*)/\1something_at_end_of_line/g

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.

HTH

1
  • 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
2

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

:g/^12138/norm!Asomething_at_the_end

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.