开发者

Text replace over number of files

I have gotten comfortable using expressions in Vim to do replaces across large files and would like to know what utility program to learn that will allow me to do such a thing across folders of files in a similar fashion. What command line program for searc开发者_如何学编程h and replace is most like vims and works across folders?


sed -i.bak 's/foo/bar/g' * 

will replace every foo with bar on every line in every file in the current directory in place and creates a backup file with .bak extension.

So I'd look into sed. But... Vim is very capable:

vim -c "bufdo!%s/foo/bar/g" -c "wqa" *

is almost the same. bufdo! executes the following command (%s/foo/bar/g in this case => replace every foo with bar on every line (% is a special line address for every line)). wqa means: write all then quit. You can specify at most 10 -c switches to Vim, which will be executed in the specified order. So, basically this is Vim automation:

  1. open every file in the current dir => every file has its own buffer
  2. execute the substitution on every buffer
  3. then write the files and quit

The only difference is the lack of backup file creation (which can be achieved easily with some .vimrc settings). But sed is faster.


probably, you should use vim not external command line program. see :help :find or :help :grep

for example, if you want to grep words across folders, pass **/*.txt.


you could do this by combining perl and bash for example:

find . -type f -name "*.cpp" -print | xargs perl -i -pe 's/pattern/replace/g' 

this will find all '.cpp' files starting at '.' and pass (pipe) each of them (the path) to perl command

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜