1

I have next files in the directory:

ls -1 file_*

file_1
file_101
file_2
file_202
file_3
file_4
file_5

In Vim I want to have these files in a numerically ordered list, like so:

['file_1', 'file_2', 'file_3', 'file_4', 'file_5', 'file_101', 'file_202']

But glob() function returns this:

echo glob('file_*', 0, 1)

" Result
['file_1', 'file_101', 'file_2', 'file_202', 'file_3', 'file_4', 'file_5']

I have found a workaround

function! Compare(i1, i2) 
    let l:f = str2nr(matchstr(a:i1, '[0-9]\+'))
    let l:s = str2nr(matchstr(a:i2, '[0-9]\+'))
    return l:f == l:s ? 0 : l:f > l:s ? 1 : -1
endfunction

echo sort(glob('file_*', 0, 1), 'Compare')

" Result
['file_1', 'file_2', 'file_3', 'file_4', 'file_5', 'file_101', 'file_202']

but interested, is it possible to force glob() function to work as I want?

  • 3
    Ultimately, if you need a sorted order, you have to sort... you might be able to pull some tricks with LANG (it affects sorted order for at least the sort utility), but you’re better off with what you have I expect – D. Ben Knoble Mar 3 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.