问题
What's the easiest way to delete the first 2 spaces for each line using VIM? Basically it's repeating "2x" for each line.
Clarification: here the assumption is the first 2 characters are spaces. So the question is about doing indentation for multiple lines together.
回答1:
Some more options. You can decided which is the "easiest way".
Remove the first 2 characters of every line:
:%normal 2x
Remove first 2 characters of every line, only if they're spaces:
:%s/^ /
Note that the last slash is optional, and is only here so that you can see the two spaces. Without the slash, it's only 7 characters, including the :.
Move indentation to left for every line:
:%normal <<
回答2:
- Enter visual block mode with
Ctrl-V(orCtrl-Qif you useCtrl-Vfor paste); - Select the area to delete with the arrows;
- Then press
dto delete the selected area.
回答3:
You could also use a search and replace (in the ex editor, accessed via the : character):
Remove first two characters no matter what:
%s/^.\{2}//
Remove first two white space characters (must be at the beginning and both must be whitespace... any line not matching that criteria will be skipped):
%s/^\s\{2}//
回答4:
Assuming a shiftwidth=2, then using shift with a range of %
:%<
回答5:
Two spaces, or two characters? (2x does the latter.)
:[range]s/^ //
deletes two blanks at the beginning of each line; use % (equivalent to 1,$) as [range] do to this for the entire file.
:[range]s/^..//
deletes the first two characters of each line, whatever they are. (Note that it deletes two characters, not necessarily two columns; a tab character counts as one character).
If what you're really doing is changing indentation, you can use the < command to decrease it, or the > command to increase it. Set shiftwidth to control how far it shifts, e.g.
:set shiftwidth=2
回答6:
I'd try one of two approaches:
- Do column editing on the block to delete using
Ctrl+V(often mapped toCtrl+Q). - Record a macro on the first row using
q1(or any other number/letter you want to denote the recording register), then replay that macro multiple times using@1(to use my previous example. Even better, use a preceding number to tell it how many times to run -10@1to run that macro 10 times, for example. It does, however, depends on what you recorded - make sure to rewind the cursor0or drop one linej, if that's relevant.
回答7:
I'd also add: learn how to configure indentation for vim. Then a simple gg=G will do the trick.
来源:https://stackoverflow.com/questions/6961705/vim-delete-the-first-2-spaces-for-multiple-lines