For example, I wish to change
1
1
2
3
5
8
13
to
1
1
2
3
5
8
13
Where this is not necessarily at the start of the line. How can I do this?
Vi and Vim Stack Exchange is a question and answer site for people using the vi and Vim families of text editors. It only takes a minute to sign up.
Sign up to join this communityFor example, I wish to change
1
1
2
3
5
8
13
to
1
1
2
3
5
8
13
Where this is not necessarily at the start of the line. How can I do this?
Move your cursor to the first single-digit number, the first 1
in this case. Type Ctrl-v
. Then move your cursor to the last single-digit number, the 8
in this case. There are several ways to move the cursor. 5j
will work. Then type
I <Esc>
where <Esc>
is the Esc
key and there is a single space between the I
and the <Esc>
. That inserts a space in front of the visually-selected block. See
:help 10.5
:help CTRL-V
:help visual.txt
set virtualedit=block
and A <Esc>
if group of lines have different lengths.
– Maxim Kim
Nov 12 '18 at 8:53
:set number
<Enter>
<ESC>
:1,6s/^/ /
Turn numbering on to make it easier to see what lines need to be changed.
In colon mode, enter the number of the first line, comma, and the last line to be changed.
Follow with s for substitution,
/^/ the ^caret searches for the beginning of the line,
/ / and insert a space (there is a space between the slashes).
In case the lines with two chars and the lines with one char is interleaved, such as
1
2
13
3
8
13
The visual block selection will not work. However, the following method still works:
:%s/\ze.\%2c$/ /
Where
\ze
marks the end of match so that only the part before it is to be substituted (with a space) (see :h /\ze
).
takes away one char\%2c
matches the second column\%2c$
means the end of line is at the second column, so that the line only contains one char:g/\%2c$/s/^/ /
where you use :global
to distinguish the pattern to search and the pattern to be replaced.
– Liu Sha
Nov 12 '18 at 2:06