Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: For Multiple Files: Copy all Text, Replace and Paste

Tags:

vim

I want to do the following for multiple files using Vim:

  1. Copy all text in each file
  2. Replace some text
  3. Paste the copied text at the end of the each file
  4. Replace some other text

Here are my commands for one file:

:%y
:%s/old1/new1/g
:G
:P
:%s/old2/new2/g

Can anybody tell me the syntax to do so? Especially that I'm new to Vim!

I found out that argdo can execute commands on multiple files. I found many examples to use argdo in replacing text, but I couldn't find the syntax to use argdo with :%y, :G, or :P

Thanks.

like image 308
Pansy Avatar asked May 04 '12 02:05

Pansy


2 Answers

Like @ib mentioned, I'd do this with ex commands1

:argdo %y | %s/old1/new1/g | $pu | %s/old2/new2/g

There's also a good chance that you might want to operate on exclusive ranges (do the first substitution only on the first part, and the second only on the second):

:argdo $mark a | %co$ | 1,'a s/old1/new1/g | 'a,$s/old2/new2/g

To allow non-matching substitutions, add s///e and add silent! to make operation much faster in the case of many files.

:silent! argdo $mark a | %co$ | 1,'a s/old1/new1/ge | 'a,$s/old2/new2/ge

1 (note that argdo expects an Ex command list by default. You'd use e.g. argdo norm! ggyG to use normal mode commands)

like image 63
sehe Avatar answered Oct 05 '22 23:10

sehe


UPD: my Vim-fu is not as strong as @ib's or @sehe's ones, so you might want to use the solutions they suggested instead of mine one.

But, my solution is easier to edit and to debug personally for me (as a Vim apprentice), so, let it be here anyway.


You can add the following temporary function in your vimrc:

function! MyTmpFunc()
   :%y
   :%s/old1/new1/g
   normal! G
   normal! P
   :%s/old2/new2/g
endfunction

Then restart Vim with the files you need to affect (something like vim myfile1.txt myfile2.txt myfile3.txt), and execute the following command:

:argdo call MyTmpFunc()

That's what you described in your question: function MyTmpFunc() will be called for each argument given to Vim.

Now you can delete MyTmpFunc() from vimrc.

Be also aware with :bufdo - it calls some command for each opened buffer. There is also :windo, which executes command for each window, but personally I found :bufdo the most useful.

Also please note that you don't have to create temporary function if you need to execute just a single command in the each buffer. Say, if you need just to replace "old1" to "new1" in the each buffer, then you can execute the following command:

:bufdo %s/old1/new1/g

and that's it.

like image 44
Dmitry Frank Avatar answered Oct 05 '22 22:10

Dmitry Frank