On Fri, Sep 22, 2006 at 07:59:37AM -0500, Tim Chase wrote:
> >Is it possible to sort lines on line length?
> >Shortes firsts, longest last?
> >If so how do you do this?
> 
> This is a common use of the "decorate-sort-undecorate" pattern. 
> You can do something like:
> 
> :%s/^/\=strlen(getline('.')).':'
> :%sort n
> :%s/^[^:]*:
[snip]

     Depending on exactly what you want, you may prefer the following
method.  This works only with vim 7!  First, define a comparison
function based on the built-in strlen() function:

  fun! MyCmp(a, b)
    let x = strlen(a:a)
    let y = strlen(a:b)
    return (x == y) ? 0 : (x < y) ? -1 : 1
  endfun

Next, yank the lines you want into a variable.  For the sake of
illustration, I will assume that you have marked them in Visual mode, so
I will use the Visual marks '< and '> :

:let a = getline("'<", "'>")

Finally, sort using the custom comparison functions and replace with
setline():

:call setline("'<", sort(a, "MyCmp"))

Yes, it can all be done in one line (exercise for the reader).

:help getline()
:help setline()
:help sort()

HTH                                     --Benji Fisher

Reply via email to