RegEx and Vim Cookbook

From Free Knowledge Base- The DUCK Project: information for everyone
Jump to: navigation, search

Instead of running Vim in a terminal window, you might want to run it in a graphical shell, ie the GUI version of Vim for Windows and Linux, GVim. It has configurable menus and toolbars that make the program's most essential features easily accessible with a mouse. It also lets you use native file dialogs and gives you the ability to resize buffer panes by clicking and dragging. The equivalent for Mac OS X is MacVim, which provides a native Cocoa user interface, including menu integration.

Delete all lines containing a pattern

The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern.

For example, to delete all lines containing "profile" (the first command is optional; it shows the lines that the second command will delete):

 :g/profile
 :g/profile/d

More complex patterns can be used, such as deleting all lines that are empty or that contain only whitespace:

 :g/^\s*$/d

To delete all lines that do not contain a pattern, use g!, like this command to delete all lines that are not comment lines in a Vim script:

 :g!/^\s*"/d

Note that g! is equivalent to v, so you could also do the above with:

 :v/^\s*"/d

The next example shows use of \| ("or") to delete all lines except those that contain "error" or "warn" or "fail" (:help pattern):

 :v/error\|warn\|fail/d

Line Feed and Carriage Return

Convert all tabs in a file to a CRLF

 :%s/\t/\r\n/g

Note: UNIX uses LF (line feed) while Macintosh previously used CR (carriage return) and Microsoft uses CRLF (\r\n).

Remove all Carriage Return ^M from file

 :%s/\r//g

Replace spaces with a new line

 :%s/\ /\r/g

Delete all blank lines form a text file

 :g/^$/d

Note: The 'g' will execute a command on lines which match a regex. The regex is the 'blank line' and the command is :d (delete).

Sort alphabetically lines in a text file

Vim has a very powerful built-in sort utility that you can use to do a quick sort.

Quick sort all lines:

 :%sort

Quick sort keep only unique lines:

 :%sort u

Reverse sort

 :%sort!

Sort numbers in numerical order:

 :sort n

Add a space character at the beginning of each line

 :%s/^/\ /