Showing posts with label ex. Show all posts
Showing posts with label ex. Show all posts

Tuesday, January 14, 2014

Removing Lines that Don't Match a Pattern

Following up on a previous tip, you can also use the "g" and "d" commands to remove lines in your current buffer that don't match a specific pattern. The following example would remove all lines that don't match "www.example.com".
:g!/www\.example\.com/d

Friday, April 10, 2009

Pull Into Ex

If you position your cursor over a given word and type :<ctrl-r><ctrl-w> it will pull the value into your current ex mode command line. This is great for yanking long values into substitutions among other things.

Thanks to Nate for the tip!

Thursday, June 12, 2008

Comment Out Line Range

This is one of my favorite ex hacks. It's pretty old school and should work all the way back to the original Vi. This assumes your comment character is # (octothorpe), but would work just as well with // comments or any other line-wise comment character. Go to column zero of the first line you want to start your comment block on. Hit ma to set a mark. Now scroll down to column zero of the last line you want to comment out. Issue the following ex command:

:'a, . s/^/# /

That's it. It runs a substitute on the range from the mark stored in register 'a to the current line. Take note that you can specify ranges for any ex command using the same technique.

Wednesday, April 9, 2008

More Global Fun

Today I had a friend ask me, "is there a way to load every line matching a pattern into a single register?" This lead me to look into a way to append to a register. I've come to find out that yanking something into a register using a capital rather than lowercase letter appends instead of overwriting the register. From there, it was just a matter of using the global command to invoke a yank on all the matches. Here's the result.

:%g/.*foo.*/normal "Ayy/

Note that `A and `a share the same register. So you can simply put using "ap (as usual). Another neat trick is a quick way to clear a register. Registers often persist among sessions (depending on your Vim setup). You can clear any register a to z as follows.

:let @a=@_

I knew there was a use for the blackhole register ;-).

Wednesday, March 5, 2008

Delete Lines Matching Keyword

Neat little trick using the global ex command to remove all lines matching a given pattern.

:g/.*foo.*/d

Of course you can use any ex command at the end and you can put in whatever pattern you'd like.

Friday, November 16, 2007

Ex Commands

Vim supports tons of ex commands, which can be very useful for efficient editing. You can get a master-list of all the ex commands Vim supports by typing :help holy-grail.