Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
421 views
in Technique[技术] by (71.8m points)

pattern matching - How to generate a number sequence in file using vi or Vim?

Is there a way to generate a number sequence in vi or Vim?

For example, for an arbitrary range of lines i ?through?j (where i?<?j) in a file opened in Vim, is there a way to generate a number sequence from?number 1 on line?i all the way through number (j???i?+?1) on line?j?

Say, I have the following lines in a file:

this is line #1
this is line #2
this is line #3
this is line #4
this is line #5
this is line #6
this is line #7
this is line #8
this is line #9
this is line #10

I want to prefix the number sequence from line?4 to line?8 with numbers?1 through?5. After the operation, the resulting file should be as follows:

this is line #1
this is line #2
this is line #3
1 this is line #4
2 this is line #5
3 this is line #6
4 this is line #7
5 this is line #8
this is line #9
this is line #10

If this is possible, is there a way to use different step sizes for the generated sequence? For example, can 2 be used for the step size instead, so that the resulting sequence is 2, 4, 6, 8, etc.?

Note: The question “How to add line numbers to range of lines in Vim?” brings up a similar problem, but it is not the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Starting with Vim 7.4.754 one can use g Ctrl-a, see :help v_g_CTRL-A

Go to line #4, use Ctrl-v to blockwise select the first character, go down 4 lines, press Shift i, enter 0 (this is 0, followed by Space) and Esc to exit insert mode.

Now use gv to re-select the previously selected area. Press g Ctrl-a to create a sequence.

I start with a 0 here, so I can re-select by gv. If you start with a 1, you need to re-select by hand while omitting the first 1.

Use 2g Ctrl-a to use a step count of 2.


screen capture demonstrating how to generate a number sequence


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...