linux - 如何通过 vim 从多个文件中添加/删除相同的文本行?

标签 linux vim debian

我在许多不同的目录中有数百个 [大部分不同的] 文件,其中都有相同的 5 行文本,我需要经常编辑这些文件。示例:

/home/blah.txt
/home/hello/superman.txt
/home/hello/dreams.txt
/home/55/instruct.txt
and so on...

这 5 行文本是按顺序排列的,但在所有 .txt 文件中都从不同的位置开始。示例:

在/home/blah.txt 中:

line 400 this is line 1
line 401 this is line 2
line 402 this is line 3
line 403 this is line 4
line 404 this is line 5

/home/hello/superman.txt:

line 23 this is line 1
line 24 this is line 2
line 25 this is line 3
line 26 this is line 4
line 27 this is line 5

我如何找到并替换所有 .txt 文件中的那 5 行文本?

最佳答案

第 1 步:打开包含所有相关文件的 vim。例如,使用 zshell,您可以:

vim **/*.txt

假设您想要的文件是当前树下任意位置的 .txt 文件。或者创建一个单行脚本来打开您需要的所有文件(看起来像:“vim dir1/file1 dir2/file2 ...”)

第 2 步:在 vim 中,执行:

:bufdo %s/this is line 1/this is the replacement for line 1/g | w 
:bufdo %s/this is line 2/this is the replacement for line 2/g | w 
...

bufdo 命令在所有打开的缓冲区中重复您的命令。在这里,执行查找和替换,然后执行写入。 :help bufdo 更多信息。

关于linux - 如何通过 vim 从多个文件中添加/删除相同的文本行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11172589/

相关文章:

c - listen() 忽略积压参数?

linux - cmake 在 Linux 上复制 Fortran 模块失败

vim - vim中,有没有插件可以用%来匹配对应的双引号(")?

unix - 如何加载已删除并存储在内存中的 .vimrc

java - 使用 java/javafx 更改 Linux 中的 Activity/应用程序菜单栏

php - 在 Debian 10 Buster 中安装 php-db 时出错

Linux NASM OUTSB 段错误

vim - VIM插入模式下重复字符

linux - 为什么gdb在core文件中提示 "Unexpected size of section ` .reg-xstate/xxxxx'?

c# - 在根目录中获取文件数组的最有效方法(如果存在)