How do I filter a visual selection through an external shell command?
Answer
!sort
Explanation
Vim can pipe a visual selection through any shell command and replace the selection with the command's output. This bridges Vim with the Unix toolchain — you can use sort, awk, tr, python, or any other tool as an ad-hoc text transformer without leaving the editor.
How it works
- Make a visual selection with
V(linewise),v(character), or<C-v>(block). - Press
!— Vim opens a prompt:'<,'>!. - Type the shell command (e.g.,
sort,column -t,python3 -c "import sys; print(sorted(sys.stdin.read()))") and press<CR>. - Vim replaces the selected region with the command's standard output.
The ! command works in Normal mode too: !{motion} filters the lines covered by the motion.
Example
Before (lines 3–6 selected with V):
banana
apple
cherry
date
Press V to select, then type: !sort
After:
apple
banana
cherry
date
Tips
- Use
!!in Normal mode to filter just the current line (e.g.,!!datereplaces the line with today's date). !{motion}column -tis handy for aligning whitespace-separated columns.- If the command produces no output or exits with an error, Vim will warn you and leave the buffer unchanged.
- Combine with
:'<,'>!python3 -m json.toolto pretty-print JSON selections.