How do I sort only a visual selection using a fixed virtual column as the key?
Answer
:'<,'>sort /\%20v/
Explanation
When lines contain aligned columns, plain :sort often gives the wrong order because it compares from column 1. This trick sorts a selected block using text that starts at a specific virtual column, which is ideal for fixed-width reports, compiler listings, and table-like logs. It lets you keep headings and surrounding context untouched by limiting the operation to your visual range.
How it works
- Enter visual line mode (
V) and select the lines you want to sort :'<,'>is the automatically inserted range for the visual selection:sort /\%20v/tells Vim to start comparison at virtual column 20\%20vis a column atom: match position at virtual column 20 (tabs/spaces aware)
Example
Given this block where the status begins around column 20:
job-a pending
job-b done
job-c failed
Select the three lines, then run:
:'<,'>sort /\%20v/
Now ordering is based on pending/done/failed instead of job-a/job-b/job-c.
Tips
- Use
:set listtemporarily if you need to inspect exact alignment before choosing the column - Combine with
:sort!for reverse order - If your key is delimiter-based rather than fixed-width, use an external sort with a field separator instead