0

I have the following input file:

abcde                                                                         
abc                                                                      
abcdef                                                                   
abcd

that I would like to sort by line-length. I can do this by running the command 1,4!awk '{print length, $0}' | sort -n -s | cut -d' ' -f2 which gives the output:

abc                                                                      
abcd                                                                     
abcde                                                                    
abcdef

Now I want to create a user-defined command SortL that will do exactly the same as above:

command! -count SortL <count>!awk '{print length, $0}' | sort -n -s | cut -d' ' -f2-

However when I run 1,4SortL on the input file I get:

abcde                                                                         
abc                                                                      
abcdef                                                                   
abcd

no changes were made so I must have made a mistake on the definition of SortL. How to define SortL so that lines get sorted by length?

2
  • 3
    see :h command-range. What you try to pass is a range, not a count. So it is -range not -count and <line1>,<line2> instead of <count> Commented Apr 13, 2018 at 11:24
  • Awesome this worked. Thanks! Commented Apr 13, 2018 at 18:19

2 Answers 2

1

Note that it can also be done in vimscript only, which has the advantage of being portable (given it's run from vim -- OK, lambda are quite recent, they are 2 years now?)

command! -range=% SortL 
   \ call setline(<line1>, 
   \              sort(getline(<line1>,<line2>),
   \                   { a, b -> strchars(a) - strchars(b)}))

BTW, strchars() will correctly count the number of glyphs in multi-bytes characters, and not the number of bytes.

Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't seem to work, I get error 121: Undefined variable: a. Also I'm not familiar with lambdas... could explain what they are?
Lambdas have been introduced in Vim 7.4.2044. If your version of Vim isn't recent enough, this won't work. Instead, you'll need to define a function and pass its Funcref to :sort().
0

Just for completeness, the answer to this is:

command! -range SortL <line1>,<line2>!awk '{print length, $0}' | sort -n -s | cut -d' ' -f2-

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.