Saturday, February 13, 2010

find and replace in a set of files using VIM

In Vim, when we need to replace text in a file, we use the substitute command.
:s/old_text/new_text/

This will replace the first occurrence of "old_text" with "new_text" for the current cursor line.

==

:%s/old_text/new_text/g

To substitute all matching occurrences in the line, add the flag 'g' which refers to global
To substitute all the file occurrences of the pattern, add the '%' before the substitute command.

====
Vim alerts if it didn't find the pattern, vim throws alert for not finding the same. So, to disable that error
add "e" with "g" option

:%s/old_text/new_text/ge
====

To apply Vim command to all the templates files, I will use the 'args' command.
will pass all the templates files in the app/views folder to 'args' using wildcards.

:args /home/venkat/files/*
to do two level directories inclusion for args
:args /home/venkat/files/*/*
====

After we passed the required files to 'args' , we can use this variable for whatever purpose we would like by using the command 'argdo'.


:argdo %s/venkat/nivvy/g | update

UPDATE MAKES THE FILES TO WRITE IF FILES ARE MODIFIED.

If the searched string is not present vim throws error and the global replacement will stop. So, to mask the error "e" option will help by tying with "g" as below

:argdo %s/venkat/nivvy/ge | update

To get confirmation for each replacement

:argdo %s/venkat/nivvy/gec | update

===

Over all

ex: to replace venkat with nivvy in set of files in a directory /home/venkat/files

:args /home/venkat/files/*
:argsdo %s/venkat/nivvy/gce | update

Interesting right :)

No comments:

Post a Comment