Multi-line vim command
Vim is a tool that I use and love because of its versatility and powerful features. Today, I’d like to bring to you the normal
command.
What is normal command?
Normal command is a command that takes a sequence of keys and pretends as though they were typed in normal mode. Confused? Let’s look at an example.
Let’s say you’re at the end of a file.
If you run :normal ggdd,
vim will hop to line 1 and delete that line.
If you run :normal $db,
vim will hop to end of current line and delete the last word.
You must be wondering, what’s the use case for it? I’m glad you asked. Let’s move to a practical example.
Let’s suppose you have a block of text below. You want to grab the text after the colon (:).
"startTime": "09:30",
"finishTime": "10:15",
"totalTime": "45m",
"amount": "$8.82",
You can follow through as described below:
- Enter visual mode
- Select all the lines
- Press <Shift+;>. You’ll see
:'<,'>
- Type
:'<,'>normal 0diWx
and hit Enter - The text changes to below
"09:30",
"10:15",
"45m",
"$8.82",
This (:'<,'>
) is a range selector which indicates all the lines that you selected in step 2. Essentially, the command 0diWx
is executed on all the lines as in a normal mode.
Let’s breakdown step 4 and understand what’s happening.
0
: Moves the cursor to the start of the linediW
: Deletes the WORD that is defined by a sequence of non-blank charactersx
: Deletes the space after the colon
Ok, so you not satisfied with the output and want to get rid of the quotes and comma and quotes. Let’s do it.
Follow the steps from 1 to 3 above and run the command below:
:'<,'>normal x$xx
You’ll end up with
09:30
10:15
45m
$8.82
Finally, you got your desired text. But it’s not Vim’s way to do things twice. We can do all this in a single go. Let’s do that now.
:'<,'>normal 0diWd2lf"D
Screencast can be found here:
That’s it for now. I hope it helped you.
If you liked it, please leave a clap.
Also, if there’s anything else you’d like to learn more of, please leave a comment.