Vim 101: Filtering for Fun and Profit
Vim supports filter commands, where a filter is a program that accepts and changes text using standard IO. I'm going to give some Unix-based examples, so the actual binaries I refer to may not be available in Windows, but the principles are the same.
Shell commands can be executed and displayed by typing :!{command}. The results can be read into the current buffer by using the :r[ead] command. For example, :r !ls will append the output from the ls Unix command into the current buffer. Typing :!! will repeat the last :!{cmd}. For more information, type :help :! when in Vim.
Rather than just executing Unix commands, filters allow text to be sent and received. The general form of the ! command is !{motion}{filter}. While in Normal mode, typing !4jsort will cause Vim to sort the next four lines. Let's break this down:
!- Filter4j- Motion, 4 lines down (expands to:.,.+4!)sort- The Unixsortcommand
To apply filters to selections, type v to enter Visual mode then press ! when a selection has been made.
Unlocking the power of filters is dependent on your knowledge of Unix text processing. A good command to know about is tr, which is used to translate characters. For example, typing !}tr "[:lower:]" "[:upper:]" will translate the current paragraph to uppercase.
If I had a set of lines that I wanted to ensure was unique, then I'd type !5juniq:
!- Filter5j- Motion, 5 lines downuniq- The Unixuniqcommand
There's been a recent resurgence of interest in using Vim and Unix as an IDE, and mastering filter commands is one way you can achieve this promised text editing nirvana.