You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Neovim中基于指定数组批量替换多行重复内容?

Neovim文本批量替换方案

问题场景

有如下目标文本:

head = cfg["head"]
head = cfg["head"]
head = cfg["head"]
head = cfg["head"]

已在Neovim中定义列表变量:

:let list = ['head', 'hhea', 'os2', 'post']

需要将文本转换为:

head = cfg["head"]
hhea = cfg["hhea"]
os2 = cfg["os2"]
post = cfg["post"]

实现方法

方法一:循环逐行替换

在命令模式下直接执行以下命令:

:let i=0 | g/head = cfg\["head"\]/execute "normal! ciw" . list[i] | let i+=1
  • let i=0:初始化索引计数器
  • g/head = cfg\["head"\]/:匹配所有包含目标内容的行
  • execute "normal! ciw" . list[i]:调用normal模式的ciw命令(修改当前单词),将匹配到的head替换为列表对应索引的元素
  • let i+=1:每完成一行替换,计数器自增,切换到列表下一个元素

方法二:全局替换结合自定义函数

  1. 先定义用于获取列表元素的函数:
:function! GetListItem(idx)
:  return list[a:idx]
:endfunction
  1. 执行全局替换命令:
:let i=0 | %s/head = cfg\["head"\]/\=GetListItem(i) . ' = cfg["' . GetListItem(i) . '"]' | let i+=1
  • %s/.../.../:对所有行执行替换操作
  • \=GetListItem(i):通过表达式动态生成替换内容,调用自定义函数取出列表对应元素
  • 每次替换后计数器i自增,依次遍历列表中的所有值

内容的提问来源于stack exchange,提问作者Carson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 23:12:32