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
- Make a visual line selection (
Vthen move) - Press
!— Vim opens the command line pre-filled with:'<,'> - Type the external command (e.g.,
sort) and press<CR> - Vim pipes the selected lines to
stdinof the command and replaces the selection withstdout
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 -uremoves duplicate lines while sorting!column -taligns columnar data with whitespace!jq '.'pretty-prints JSON selections!awk '{print NR". "$0}'prefixes lines with numbers- Works on entire files too:
gg!Gsortsorts the whole buffer - Without a visual selection,
!!{cmd}filters the current line - Combine with
=for indentation or usegqfor text wrapping as lighter alternatives