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

How do I pipe a visual selection through an external command and replace it with the output?

Answer

!{command}

Explanation

In visual mode, pressing ! followed by an external command pipes the selected lines through that command and replaces the selection with the output. This turns Vim into a text-processing powerhouse by leveraging shell tools like sort, uniq, column, awk, and jq directly on your buffer content.

How it works

  1. Make a visual line selection (V then move)
  2. Press ! — Vim opens the command line pre-filled with :'<,'>
  3. Type the external command (e.g., sort) and press <CR>
  4. Vim pipes the selected lines to stdin of the command and replaces the selection with stdout

The key sequence expands to :'<,'>!{command} on the command line, where '< and '> are the visual selection marks.

Example

Given these unsorted lines selected with V3j:

zebra
apple
mango
banana

Press !sort<CR> and the selection becomes:

apple
banana
mango
zebra

Tips

  • !sort -u removes duplicate lines while sorting
  • !column -t aligns columnar data with whitespace
  • !jq '.' pretty-prints JSON selections
  • !awk '{print NR". "$0}' prefixes lines with numbers
  • Works on entire files too: gg!Gsort sorts the whole buffer
  • Without a visual selection, !!{cmd} filters the current line
  • Combine with = for indentation or use gq for text wrapping as lighter alternatives

Next

How do I rename a variable across all case variants (snake_case, camelCase, MixedCase) at once?