我正在使用一个YAML文件,它有一个整数作为ID,每4-6行出现一次.我希望在此文件的中间添加一条记录(为了便于阅读),以保持顺序编号的完整性.
文件格式如下.有任何想法吗?
- id: 1
type: string
option: diff_string
other: alt_string // note: 'other' option does not appear for all records
- id: 2
type: string
option: diff_string
//new record would go here as id: 3, increasing id: # of all following records by 1
- id: 3
type: string
option: diff_string
other: alt_string
Run Code Online (Sandbox Code Playgroud)
我相信你可以通过将计数器(这里:变量g:I
)设置为1 来实现你想要的效果:
let g:I=1
Run Code Online (Sandbox Code Playgroud)
然后在匹配的每一行上执行替换^- id: \d\+$
:
%g/^- id: \d\+$/ s/\d\+/\=g:I/|let g:I=g:I+1
Run Code Online (Sandbox Code Playgroud)
该替换使用\=
thingy(参见:help sub-replace-expression
)替换\d\+
实际值g:I
.在替换之后,计数器递增(let g:I=g:I+1
).
随着g/^- id: \d\+$/
你保证substition仅在线路匹配执行^- id: \d\+
.
编辑如果要为其创建地图,可以将以下代码段放入.vimrc:
nnoremap resync :let g:I=1<CR>:%g/^- id: \d\+$/ s/\d\+/\=g:I/\|let g:I=g:I+1<CR>
Run Code Online (Sandbox Code Playgroud)
它允许重新同步通过键入您的IDS resync
在正常模式.
需要注意的转义|
与\
和使用<CR>
,你会按enter键.