How do I transform text in a visual selection using awk or sed?
Answer
:'<,'>!awk '{print toupper($0)}'
Explanation
Vim can pipe any visual selection through external Unix commands and replace the selection with the output. Using awk, sed, sort, tr, or any command-line tool lets you perform transformations that would be complex in pure Vimscript.
How it works
- Select text in visual mode (v, V, or
<C-v>) !— triggers the filter command- The selection is sent to the command's stdin
- The command's stdout replaces the selection
Example
:'<,'>!awk '{print toupper($0)}'
Before:
hello world
foo bar
After:
HELLO WORLD
FOO BAR
Reverse field order:
:'<,'>!awk '{print $2, $1}'
Tips
- Use
sedfor substitutions::'<,'>!sed 's/old/new/g' - Chain commands with pipes:
:'<,'>!sort | uniq -c | sort -rn - Use
trfor character transforms::'<,'>!tr '[:lower:]' '[:upper:]' - Press
uto undo if the result isn't what you expected