0

Ctrl-A is very useful for incrementing the first number in line, but what if the number you want to increment is not the first one?

for an example, if want to make,

Section. 1-1
Section. 1-2
Section. 1-3

How would you do it?

2
  • Do you want a solution that would work no matter what text is on the line, or a solution that would work for your example? And do you want to increment the second number on every line, or just one of them? – James Aug 30 '19 at 20:22
  • Thank you for the reply. I am looking for a solution that works with no matter what else is on the line. and I think I want to find the one that works for one line, so I can expand it to work with multiple lines. – M.O. Kitzka Aug 30 '19 at 20:37
0

OK. I found a way to do this. I'm sure somebody has a better suggestion, but this is a start. first of all,

Ctrl-A jumps the cursor to the next number and increments, and
Ctrl-x jumps the cursor to the next number and decrements, 

combine this with a search,

/\d\+

which simply gets your cursor to the next number, you can make a macro to do this.

for the example question,

qa
^
/\d\+
n
ctrl-x
q

will make a macro that increments the second number of a given line. A trick is to have the n(ext) to get to the second number, and use ctrl-X instead of ctrl-A in this case, because vi thinks that hyphen as a negative sign. If you use ctrl-a, it actually decrements the subsection number.

Now, we can use the n(ext) to increment any nth number. I mean, first type,

section 1-3.2.2.10

then, put the cursor to that line, then

qa
yy
p
/\d\+
3n
ctrl-a
q

to record a macro, then,

4@a 

will make,

Section 1-3.2.2.10
Section 1-3.2.3.10
Section 1-3.2.4.10
Section 1-3.2.5.10
Section 1-3.2.6.10

Alternatively, (Thank you, Rich!) If we are incrementing the last number, we can do it much simply,

qa
yy
p
$
ctrl-a
q

then

4@a

to get

section 1-3.2.2.10
section 1-3.2.2.11
section 1-3.2.2.12
section 1-3.2.2.13
section 1-3.2.2.14
3
  • Is the example at the end simplified deliberately? $ seems like a simpler way to get to the last number on the line in this example! – Rich Aug 30 '19 at 22:17
  • Thank you, Rich! Yes, that works! I did not realize it. I edited it to reflect your suggestion. – M.O. Kitzka Sep 3 '19 at 17:16
  • If your numbers are in a column, you can also do it using visual mode (without a macro), too. For your specific example: yy4p$<C-V>3jg<C-A>. See :help v_g_CTRL-A – Rich Sep 4 '19 at 8:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.