Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

External GNU BinUtils "Sort" by column won't work in VIM

I have a simple table of data in VIM consisting of two sets of variable-length strings. For example:

test bob
check mike
review tom
test2 tom
presentation mike

I have been able to make it "prettier" by piping it through column, by selecting all five lines in VIM using CTRL+V, selecting all five entire lines visually, then hitting the SHIFT+: key combination to enter command mode, and then issue the command '<,'>!column -t, which makes it look like:

test          bob
check         mike
review        tom
test2         tom
presentation  mike

Now, I would like to finally sort by the second column. I tried doing a visual block selection, and using '<,'>!sort -n -k2, but I just get:

check         mike
presentation  mike
review        tom
test          bob
test2         tom

So, it sorts, but only by the first column. Thinking this uses perhaps the literal column number rather than assuming SPACE as a delimiter, and accounting for consecutive delimiters, I tried again with '<,'>!sort -n -k15, but I still get the same undesired behavior.

How can I get this to sort by the second column, either by the literal column number (ie: 15), or by the visual column number (ie: 2)?

Thank you.

like image 353
Cloud Avatar asked Aug 14 '26 19:08

Cloud


2 Answers

this command:

%sor r /\S\+$/

generates:

test          bob
check         mike
presentation  mike
review        tom
test2         tom

check :h :sort for details

your block-wise visual selection won't help sorting (either built-in or external). because it passed a range, which is line based, even though the selection looks in block/column wise. :h range for detail. If you want to use external sort, you should do exactly same as in shell.

like image 160
Kent Avatar answered Aug 17 '26 00:08

Kent


Try setting the separator like this:

'<,'>!sort -t' ' -k2

(not that there is no -n flag)

From the manual (man sort):

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

For me it makes:

check         mike
presentation  mike
review        tom
test2         tom
test          bob

Become:

test          bob
presentation  mike
check         mike
review        tom
test2         tom
like image 43
Reut Sharabani Avatar answered Aug 16 '26 22:08

Reut Sharabani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!