Editing Files with Vim in Linux

January 28
blog author

Appno Blogger

Appnovation Coop

Vim is a powerful text editing tool included in almost every distribution of Linux. While many people may like a GUI text editor like Microsoft Word, vim is often more useful in the server environment, such as modifying a server configuration file or creating a bash script. Here are a few examples of common commands in vim that one may find useful (command mode):

1) dfm which deletes characters from cursor till the first 'm' in the line

2) :3,7d which deletes all lines between line 3 and 7 (inclusive)

3) :g/pattern/d which deletes lines that contain a particular pattern (regular expression can play its role here), eg. :g/^$/d would delete all empty lines

4) :g/pattern/.-2,.d which deletes each line that contains the pattern and its previous 2 lines

5) :g!/pattern/d (or :v/pattern/d) which deletes all lines that do not contain a pattern

6) :%s/pattern/replacement/g (or :1,$s/pattern/replacement/g) which substitutes the pattern in all lines with a replacement, eg. :%s/morning/evening/ig would replace all strings 'morning' (i for case-insensitive) with 'evening' in all lines

7) :10,50s/pattern/replacement/g which does the same thing as the previous command except that the substitution is carried out between line 10 and 50

8) :s/\<[a-z]/\u&/g which capitalizes the first character of all words on current line (where cursor is)

9) :%!sort which sorts all lines in the file

10) :r !ls which executes the 'ls' command and inserts its output below the cursor

11) :r filename.txt which inserts the content of the file 'filename.txt' below the cursor

12) :g/^/exe ".w "."filename.".line(".") which would create a new file for each line of current file (eg. filename.1, filename.2, filename.3, etc.)

For more details about vim, please visit http://vimdoc.sourceforge.net/.

A list of vim plugins can be found at http://www.vim.org/scripts/script_search_results.php.