I have so many huge size of files and always need to do search and replacement
so I map the command as nnoremap aa :let i=1 \| g/regexp/ s/^/\=printf("%1d. ",i)/g \|let i =i+1\|:w! 1.txt

This cmd include a loop and count , I want to save as modified file as a new file and keep the original one.
But this cmd \|:w! 1.txt will save the file again and agian take so many time, I just want to save the final one when all the action completed.
I know i can use two steps to achieve it

  1. :let i=1 \| g/regexp/ s/^/\=printf("%1d. ",i)/g \|let i =i+1
  2. :w! 1.txt

Is there any way to achieve it in one cmd line?

1 Answer 1



The problem is that global takes all the rest of its arguments as the command to execute on matching lines. But you can manipulate what it sees with execute:

let i=1 | execute 'global/regexp/substitute/^/\=printf("%1d. ",i)/g | let i =i+1' | :write! 1.txt

As you’ve noticed, you need to be careful with bars in mappings; I find the layers introduced by also using execute with bars can sometimes be confusing, so I recommend putting the above into a function and having your mapping invoke that.

  • WOW!!Really Thanks, I add execute to every cmd with :g it really speedup
    – M_Sea
    Commented Nov 8, 2023 at 14:36

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.