Vim increment number at irregular rows
Vim increment number at irregular rows — practical walkthrough with examples.
Suppose you have a JSON structure with repeated _iteration fields that all have the same value (e.g. 0), and you need to renumber them sequentially. Here is the initial state:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
[{
"payload": {
"data": {
"vlan_id": 27,
...
}
},
"_response": 200,
...
"_iteration": 0 <---
}, {
"payload": {
"data": {
"vlan_id": 27,
...
}
},
"_response": 400,
...
"_iteration": 0. <---
The following Vim command uses :g (global) to find every line containing _iteration, then substitutes the first number on that line with an auto-incrementing counter. The variable c starts at 1 and increases by 1 after each replacement.
1
:let c=1 | g/_iteration/ s/\d\+/\=c/ | let c+=1
Result
After running the command, every _iteration value is replaced with a unique sequential number:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
[{
"payload": {
"data": {
"vlan_id": 27,
...
}
},
"_response": 200,
...
"_iteration": 1
}, {
"payload": {
"data": {
"vlan_id": 27,
...
}
},
"_response": 400,
...
"_iteration": 2
...
This post is licensed under CC BY 4.0 by the author.