I need to replace multiple lines using vi. For example, any numbers_Apple to Apple







  • 1
    Welcome to Vi and Vim! I've edited your question to include some formatting. I left the blank lines in since I wasn't sure if they were part of your sample file or not; you should remove them if not. You might also want to run vimtutor, browse the :help, or (sincerely) google—we want to help here, but Qs like this have been asked and answered for a long time. Plenty of resources exist explaining how to do this.
    – D. Ben Knoble
    Jul 28 at 14:38

"Search and replace" and "regex" (regular expressions) are how you achieve this kind of task. Websearching those terms will yield lots of information.

Vim's search and replace functionality is done from "normal" mode by typing : and then the search replace pattern, like :%s/searchforthis/replacewiththat/g (it's similar to sed in the Linux command line environment).

So for your case you can do :%s/[0-9]*_//g to simply delete the part of the pattern you don't want... unless that deletes too much, then you could enhance... like :%s/[0-9]*_Apple/Apple/g.

  • 1
    Well, sed is similar to ed, but for streams, and vim descends from vi descends from ex descends from ed… all of which include the s command. I would point out (since the asker seems unaware) the relevant help topics, including the docs for patterns, and also that the range and flags in the command are flexible.
    – D. Ben Knoble
    Jul 28 at 11:29
  • 1
    Also [0-9] is just \d in vim
    – D. Ben Knoble
    Jul 28 at 11:30
  • ... and the vast majority of other regex flavors.
    – Zoe
    Jul 28 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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