vimtricks.wiki Concise Vim tricks, one at a time.

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

  1. Make a visual selection with V (linewise), v (character), or <C-v> (block).
  2. Press ! — Vim opens a prompt :'<,'>!.
  3. Type the shell command (e.g., sort, column -t, python3 -c "import sys; print(sorted(sys.stdin.read()))") and press <CR>.
  4. 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., !!date replaces the line with today's date).
  • !{motion}column -t is 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.tool to pretty-print JSON selections.

Next

How do I visually select a double-quoted string including the quotes themselves?