如何在 Vim 中自动编辑多个文件? [英] How to automat editing of several files in Vim?

查看:69
本文介绍了如何在 Vim 中自动编辑多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多文件,我想在每个文件中删除第 1 到 55 行,在第 25 行到第 35 行添加注释引导符(例如,//),然后将更改保存到新文件.

I have a multitude of files in each of which I want to, say, delete lines 1 through 55, add a comment leader (e.g., //) on lines 25 through 35, and then save the changes to a new file.

如何单独使用 Vim 或在 Bash 脚本的帮助下自动执行此操作?

How can I do this automatically with Vim alone or together with the help of a Bash script?

推荐答案

尽管使用 edsed 是一种常见做法1在这种情况下,有时使用 Vim 会方便得多.的确,不是盲目地编写类似 ed 的脚本,而是经常更容易首先使用其中之一执行所需的操作在 Vim 中以交互式文件:

Despite the fact that using ed or sed is a common practice1 in such cases, sometimes using Vim is much more convenient. Indeed, instead of writing an ed-like script somewhat blindly, it is often easier to first perform the desired manipulations with one of the files interactively in Vim:

vim -w log.vim file1.txt

然后对其余文件重复此操作:

and then repeat it on the rest of the files:

for f in file*.txt; do vim -s log.vim "$f"; done

对于您的示例用例,log.vim 文件可能包含类似以下内容:

For your example use case, the log.vim file will likely have contents similar to the following:

gg55dd:25,35s/^/\/\/ /
:w %_new
:q!

请注意,要使用新名称保存文件,您不应键入它直接,而是使用 % 替换,如上所示 - 否则以下所有文件的所有修改都将保存到同一个文件,每次都覆盖其内容.或者,您可以事先复制文件,然后就地编辑副本(通过简单地发出 :w 命令保存每个参数).

Note that to save the file with new name you should not type it directly, but rather use the % substitution, as shown above—otherwise all the modifications of all the following files will be saved to the same file, overwriting its contents every time. Alternatively, you can duplicate the files beforehand and then edit the copies in place (saving each of them by simply issuing the :w command without arguments).

这种方法的优点是您可以进行所有更改以交互方式,确保您在至少在其中一个文件上,在对其余文件执行编辑之前其中.

The advantage of this approach is that you can make all of the changes interactively, ensuring that you are getting the intended result at least on one of the files, before the edits are performed for the rest of them.

1 当然,您也可以以类似 ed 的方式使用 Vim:

1 Of course, you can use Vim in an ed-like fashion, too:

for f in file*.txt; do vim -c '1,55d|25,35s/^/\/\/ /|w! '"${f}_new"'|q!' "$f"; done

这篇关于如何在 Vim 中自动编辑多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆