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

Vim如何匹配多行并为指定区间内每行添加#注释前缀?

批量注释指定代码区块内的所有行

原始文件内容

# For testing
Space 5 ;
Width 8 ;
Length 10 ;
" ;

# normal line
Space 5 ;
Width 8 ;
Length 10 ;
" ;


# For testing
Space 5 ;
Width 8 ;
Length 10 ;
" ;

需求

注释掉所有位于# For testing和" ;之间的行(包括这两个标记行),给每行添加#作为前缀,其他区块保持不变。期望效果:

# For testing
#Space 5 ;
#Width 8 ;
#Length 10 ;
#" ;

# normal line
Space 5 ;
Width 8 ;
Length 10 ;
" ;


# For testing
#Space 5 ;
#Width 8 ;
#Length 10 ;
#" ;

解决方案(Vim环境)

直接执行以下命令即可完成批量注释:

:g/# For testing/,/" ;/norm I#

命令解释

  • :g/# For testing/,/" ;/:定位所有以# For testing开头、以" ;结尾的连续行区块
  • norm I#:对每个区块内的每一行,在normal模式下执行**行首插入#**的操作,实现注释效果

如果偏好正则替换的方式,也可以用这条命令:

:%s/\(# For testing\)\(\_.\{-}\)\(" ;\)/\1\n\=substitute(submatch(2), '\v^', '#', 'g')\3/g

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:18:19