How do I align columns in a visual selection using an external command?
Answer
:'<,'>!awk '{printf "%-20s %s\n", $1, $2}'
Explanation
By piping a visual selection through awk with printf formatting, you can align columns to fixed widths. This is a quick way to format tabular data without plugins, leveraging Unix tools directly from Vim.
How it works
:'<,'>!— pipe the visual selection through an external commandawk '{printf ...}'— formats each line with fixed-width columns%-20s— left-align in a 20-character-wide field- The output replaces the selected text
Example
:'<,'>!awk '{printf "%-20s %s\n", $1, $2}'
Before:
name value
longer_variable_name 42
x 100
After:
name value
longer_variable_name 42
x 100
Tips
- Use
column -tfor simpler auto-alignment::'<,'>!column -t - For more columns, extend the printf:
"%-15s %-10s %s\n", $1, $2, $3 - Use
sort -k2to sort by the second column simultaneously - The
columncommand is often simpler::'<,'>!column -t -s','for CSV data