Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you sort a range of lines by length?

Tags:

regex

vim

sorting

Often I just want to sort all my #include's at the top of my source and header files by their length.

vim allows me to sort alphanumerically in a similar manner with :{range} sort u.

In vim, how do you sort a range of lines by the length of the line? Such that shorter lines are followed by longer lines.

Searching the internet, I found this:

:% s/.*/\=printf("%03d", len(submatch(0)))."|".submatch(0)/ | sor n | %s/..../ 

But that only works to sort the entire file, and is black magic to me anyway. I'm trying to figure out how to do that same sort with a range such as from line 4 to 18, as in :4,18 s/... Do you have any ideas?

like image 642
Cory Klein Avatar asked Jul 17 '12 21:07

Cory Klein


People also ask

How do I sort by length in Word?

Select the list you want to sort by the character length, and click Enterprise > Advanced Sort. See screenshot: Step 2. Then the Advanced Sort dialog display on the screen, select the column your list in, and choose Text length from the Sort On drop down list, and specify the Order you need.

How do I sort by length in Notepad ++?

Notepad++ has a built-in TextFX tool that sorts selected lines alphabetically. This tool can be hijacked to sort by the length of the lines by placing spaces on the left of each line, and making sure that all the lines are the same length.

How do I find the length of a line in Notepad ++?

Click View → Summary. Double-click on Length / Lines on the Status Bar (shortcut to Summary) Use TextFX → TextFX Tools → Word Count.


1 Answers

Filter Visual Selection with Awk

One way to do this in vim is by filtering the visual selection with awk's length() function before sorting. For example:

:'<,'> ! awk '{ print length(), $0 | "sort -n | cut -d\\  -f2-" }' 
like image 143
Todd A. Jacobs Avatar answered Oct 14 '22 12:10

Todd A. Jacobs