推荐方法:
If you’re on a Unix-like system (FreeBSD, Linux, macOS), use :14,19!tac
.
来自chatgpt
To reverse the display order of lines 51 to 54 in Vim, you can use the :g
and :tac
-style command combination.
Here’s the most direct and idiomatic way to do it:
:51,54g/^/m51-1
Explanation
-
:51,54
→ selects lines 51 through 54. -
g/^/
→ applies the following command (m51-1
) to each line matching the regex^
(i.e., every line in the range). -
m51-1
→ moves the current line just before line 51.
Because Vim executes this for each line in top-to-bottom order, the sequence is reversed.
Step-by-step result
Suppose lines 51–54 originally are:
line51
line52
line53
line54
After executing the command, they become:
line54
line53
line52
line51
Notes
-
You can use
:.,.+3g/^/m.-1
to do the same for “current line to current+3”. 这个方法,我尝试了下,没成功。 -
Always use line numbers or marks (
'a
,'b
) to ensure the correct range.
Would you like me to show a macro-based or visual-mode method too (for more interactive editing)?
Another good ways:
To reverse lines 14 through 19 in Vim (i.e., make line 19 become 14, 18 become 15, etc.), you can do this directly from Normal mode with a range and an Ex command.
Here’s the precise command:
:14,19!tac
Explanation:
-
:
— enters command-line (Ex) mode. -
14,19
— specifies the line range (lines 14 through 19). -
!tac
— filters that range through the external Unix commandtac
, which reverses lines.
This will replace lines 14–19 with their reversed order.
If You’re on Windows (without tac
):
Vim on Windows doesn’t have tac
by default. You can simulate it using Vimscript:
:14,19g/^/m14
Explanation:
-
g/^/
— matches all lines (from the specified range). -
m14
— moves each matched line after line 14, effectively reversing the block.
However: this command reverses relative to the top of the range, so if you start at line 14, it works cleanly.
Another Pure-Vim Method (portable across systems):
:14,19y a | 14,19d | put! a
Step-by-step:
-
:14,19y a
— yank (copy) lines 14–19 into registera
. -
:14,19d
— delete the original lines. -
:put! a
— put (paste) them reversed (the!
means before the current line, reversing the order).
That’s the most reliable Vim-only way.
✅ Recommendation:
If you’re on a Unix-like system (FreeBSD, Linux, macOS), use :14,19!tac
.
If you want a Vim-only portable method, use the yank–delete–put trick.
Would you like me to give you a one-key macro that reverses any visually selected lines automatically?