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

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 command
  • awk '{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 -t for simpler auto-alignment: :'<,'>!column -t
  • For more columns, extend the printf: "%-15s %-10s %s\n", $1, $2, $3
  • Use sort -k2 to sort by the second column simultaneously
  • The column command is often simpler: :'<,'>!column -t -s',' for CSV data

Next

How do I return to normal mode from absolutely any mode in Vim?