在 VIM 中排序单词(不是行) [英] Sorting words (not lines) in VIM

查看:12
本文介绍了在 VIM 中排序单词(不是行)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

内置的 VIM :sort 命令对文本行进行排序.我想在一行中对单词进行排序,例如变换线

The built-in VIM :sort command sorts lines of text. I want to sort words in a single line, e.g. transform the line

b a d c e f

a b c d e f

目前我通过选择该行然后使用 :!tr ' ' ' ' |排序 |tr ' ' ' ',但我相信有更好、更简单、更快捷的方法.有吗?

Currently I accomplish this by selecting the line and then using :!tr ' ' ' ' | sort | tr ' ' ' ', but I'm sure there's a better, simpler, quicker way. Is there?

请注意,我使用 bash,因此如果有一个更短、更优雅的 bash 命令来执行此操作,也可以.

Note that I use bash so if there's a shorter and more elegant bash command for doing this it's also fine.

我的用例是我有一行写着 SOME_VARIABLE="one 二三四等" 并且我希望该变量中的单词是排序,即我想要 SOME_VARIABLE="etc 四一三二".

My use-case is that I have a line that says SOME_VARIABLE="one two three four etc" and I want the words in that variable to be sorted, i.e. I want to have SOME_VARIABLE="etc four one three two".

最终结果最好可以映射到快捷键,因为这是我发现自己经常需要的东西.

The end result should preferably be mappable to a shortcut key as this is something I find myself needing quite often.

推荐答案

利用你的回答中的好主意,尤其是 Al 的回答,我最终想出了以下几点:

Using great ideas from your answers, especially Al's answer, I eventually came up with the following:

:vnoremap <F2> d:execute 'normal i' . join(sort(split(getreg('"'))), ' ')<CR>

这会在visual 模式下映射F2 按钮以删除所选文本、拆分、排序和连接它,然后重新插入它.When the selection spans multiple lines this will sort the words in all of them and output one sorted line, which I can quickly fix using gqq.

This maps the F2 button in visual mode to delete the selected text, split, sort and join it and then re-insert it. When the selection spans multiple lines this will sort the words in all of them and output one sorted line, which I can quickly fix using gqq.

我很高兴听到有关如何进一步改进的建议.

I'll be glad to hear suggestions on how this can be further improved.

非常感谢,我学到了很多:)

Many thanks, I've learned a lot :)

EDIT:将 '"' 更改为 getreg('"') 以处理带有字符 <代码>'在里面.

EDIT: Changed '<C-R>"' to getreg('"') to handle text with the char ' in it.

这篇关于在 VIM 中排序单词(不是行)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆